Unable to create a closure for a function inside of object instance to send to another object

StackOverflow https://stackoverflow.com/questions/23268472

  •  08-07-2023
  •  | 
  •  

Domanda

I have this :

objectA .....

objectB = function (){
    value:1,
    do_things: function (param1, param2, option) {bla bla},
    connect : function  (dest){
        My_objectA.set_external_do_thing  = function  ?????????
    }
}

Then I have :

MY_objectA = new objetA();
MY_objectB = new objetB(); 
MY_objectB.connect(My_objectA);

I'd like to write the right code to send a do_things function to ObjectA and then call it from there. do_things uses local variables param1 and param2. I need to set them but I can't.

By now I have a lot of undefined messages I can't solve. Any help would be appreciated.

È stato utile?

Soluzione

As @Bergi right said you made some mistakes, I fix them and tried to implement a sample from what I understand is your doubt... take a look...

Assume that you have two objects:

var husband = {
    spentFactor: 1,
    buyThings: function () {
      console.log('bla bla');
    },
    buyOtherThings: function (param1) {
      console.log("Final Cost: " + (param1*this.spentFactor));
    }
};

var wife = {
    spentFactor: 10,
    buyThings: function () {
      console.log('bla bla');
    }
};

then if you want to use buyOtherThings() method from husband object, but you know we man have a different spent factor:

husband.buyOtherThings(20);
husband.buyOtherThings.apply(wife, [20]);

The apply() method is the key, every function descend from a Function object and you inherits this by default. This method permit that you change the this from a object, so we can reuse a function from a different object.

play around this code here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top