Relying on this
in the wrong context is a common pitfall. A contrived example:
function SomeClass() {
this.prop = 42;
document.body.addEventListener('click', function() {
alert(this.prop); // will be undefined
});
}
new SomeClass();
One way around this is using bind
(or call
or apply
), for example:
function SomeClass() {
this.prop = 42;
document.body.addEventListener('click', (function() {
alert(this.prop); // works
}).bind(this));
}
new SomeClass();
Another option is to make a reference to this
available via closure, usually _this
or self
:
function SomeClass() {
var _this = this;
this.prop = 42;
document.body.addEventListener('click', function() {
alert(_this.prop); // works
});
}
new SomeClass();
I prefer the latter method, because I can declare it once rather than wrapping loads of functions with bind()
, and nested callbacks (which I know are not ideal, but are seen in the wild) become simpler. But I have the sneaking suspicion that either a) there are gotchas with this method, or b) the fact that I have to do this or bind
in the first place means that I'm doing it wrong. Any thoughts?