I've already done a similar question , however this time I have a somewhat more complex problem:
/ p>
ObjectTest1 = (function(){
var init = function(){
this.callback = null;
}
init.prototype = {
setCallback : function(callback){
this.callback = callback; // O CALLBACK DEFINIDO AQUI É init.prototype.methodTest2 PERTENCENTE AO ObjectTest2
},
applyCallback : function(){
if(typeof this.callback == 'function'){
this.callback(); // CHAMADA NORMAL DE init.prototype.methodTest2 DO OBJETO ObjectTest2
}
}
}
return init;
}());
ObjectTest2 = (function(){
var init = function(){}
init.prototype = {
methodTest1 : function(){
console.log('methodTest1');
},
methodTest2 : function(){
console.log('methodTest2');
var self = this; // AQUI this PASSA A SER ObjectTest1 MESMO EU NÃO TENDO USADO .call OU .apply
if(typeof self.methodTest1 != 'undefined'){ // ESTE METODO NÃO EXISTE NO ObjectTest1 POIS ELE É DO ObjectTest2
self.methodTest1();
}else{
console.log('ERROR');
}
}
}
var newInit = new init;
return newInit;
}());
var o = new ObjectTest1();
o.setCallback(ObjectTest2.methodTest2);
o.applyCallback();
Doubt
- Why did this change if I made a normal method call?
- How can I make sure I do not lose the this reference of the object I am currently in?
Summary
I instantiate the ObjectTest1
and set it as callback a method of ObjectTest2
which in turn when executing should call another method of itself.