8
I had already made one similar question, however this time I am with a problem a little more complex :
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
- Because the this was changed if I made a normal method call?
- How can I not miss the reference this of the object I am currently?
Summary
I instate the ObjectTest1
and I set as callback a method of ObjectTest2
which in turn when being executed should call another method of itself.
It really is a valid answer and it revolves my problem perfectly, however I believe it is more applicable the answer of @Wallace, because if I want to change to
return init;
each instance would have to have its own scope ofself
.– Guilherme Lautert