I wrote something like this:
window.onload = function() {
var a = new A();
a.init();
};
A = function() {
this.b = {};
};
A.prototype = {
init : function() {
document.writeln("init");
this.b = new B();
this.b.doCallback(this.init2);
},
init2 : function() {
document.writeln("init2");
this.b.say();
}
};
B = function(){};
B.prototype = {
doCallback: function(callback){
callback();
},
say: function(){
document.writeln("I'm B");
}
};
For me output should look like this:
init
init2
I'm B
But insted, it looks like that:
init
init2
Chrome says that method ‘say’ is undefined. Could someone explain me why?
It is because in your code
thisdoes not represent an instance of B.https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this
So when you are calling
callbackwhich isinit2,this.bisnulland does not have anysaymethod.If you are using jQuery, you could use the method proxy http://api.jquery.com/jQuery.proxy/