When you have an anonymous callback, this
usually refers to the window
object. A good example is with setTimeout
:
var someObject = {
set: function() { /* ... */ },
doSomething: function() {
// right here, "this" is "someObject"
setTimeout(function() {
// whereas right here, "this" is "window"
});
}
}
A lot of people solve this conflict like this:
var someObject = {
set: function() { /* ... */ },
doSomething: function() {
var that = this;
setTimeout(function() {
console.log(that) // => now it refers to "doSomething"
});
}
}
That's where bind
comes into play.
See this jsfiddle:
var someObject = {
set: function() { /* ... */ },
doSomething: function() {
setTimeout(function() {
console.log(this) // => now it refers to "doSomething"
}.bind(this));
}
}
Edit
Felix Kling made a good comment on this answer. For this answer, I'm assuming you're calling someObject.doSomething()
, and not calling the doSomething()
method a different context.