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,
thiscan be kind of tricky in Javascript. The problem is that its value depends on how you call the function.The usual workaround is passing a wrapper callback like you did in b), except that the common name for the
mevariable isthat(you sometimes seeselftoo)The other alternative is to use the bind method from functions
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