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