In the following code, when func2b is called, ‘this’ is the DOMWindow, and not a reference to obj2. Why is func2b loosing it’s reference to obj2 as ‘this’?
Here’s a version on jsFiddle: http://jsfiddle.net/qqzKh/
var obj1 = {
init: function() {
this.prefix = "Stop!";
obj2.func2a(this.func1a);
}
,func1a: function(message) {
console.log(this.prefix + " " + message);
}
};
var obj2 = {
func2a: function(callback) {
this.callback = callback;
console.log(this.callback); // Correct reference to obj1.func1a
obj3.func3a(this.func2b);
}
,func2b: function(message) {
console.log(this); // Unexpectedly returns DOMWindow
this.callback(message);
}
};
var obj3 = {
func3a: function(callback) {
callback("Hammer Time.");
}
}
obj1.init();
SOLUTION
var obj1 = {
init: function() {
this.prefix = "Stop!";
obj2.func2a(this, this.func1a);
}
,func1a: function(message) {
console.log(this.prefix + " " + message);
}
};
var obj2 = {
func2a: function(owner, callback) {
this.owner = owner;
this.callback = callback;
obj3.func3a(this, this.func2b);
}
,func2b: function(message) {
this.callback.call(this.owner, message);
}
};
var obj3 = {
func3a: function(owner, callback) {
callback.call(owner, "Hammer Time.");
}
}
obj1.init();
if you do:
then a is called ‘this’ in the body of f.
if you do:
then window is called ‘this’ in the body of f.
Edit: as Esailija said:
you’re using callback(“Hammer Time.”) like f() is called in this answer.