I have an object with a method that I’d like to pass to a function as a callback. However, inside the callback, this
no longer refers to my object. Why not?
I’m familiar with using a variable to get around the problem when passing a function literal:
var obj = {
a: function () {
var me = this;
console.log(this);
setTimeout(function () {
console.log(this); // Not obj
console.log(me); // This works!
}, 100);
}
};
How can I fix it in this case?
var obj = {
b: function () {
setTimeout(this.callback, 100);
},
callback: function () {
console.log(this); // =(
}
};
Yes, this
can be kind of tricky in Javascript. The problem is that its value depends on how you call the function.
obj.callback(); //ok
var f = obj.callback;
f(); //does not look like a method call
//Javascript does not pass the this!
The usual workaround is passing a wrapper callback like you did in b), except that the common name for the me
variable is that
(you sometimes see self
too)
var that = this;
setTimeout( function(){ return that.callback(); }, 300);
The other alternative is to use the bind method from functions
setTimeout( this.callback.bind(this) , 300)
Note that bind is not supported in IE 8 (you might need a shim in that case).
For more:
Maintaining the reference to "this" in Javascript when using callbacks and closures
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With