Just ran into a binding problem that’s right on the edge of my Javascript universe, so I’m going to talk my way through it, as Regis recommends, and arrive at my question:
function foo() {
document.body.addEventListener("click", this.bar);
}
foo.prototype.bar = function(evt) {
alert(this);
}
test = new foo();
This alerts with the document.body element, since the this is lost due to the function reference. So, the reference must use bind() to persist the reference:
function foo() {
document.body.addEventListener("click", this.bar.bind(this));
}
This alerts with the expected object of type foo.
But, according to this table, a pile of browsers won’t play nice if I use bind(). I’ve been reading up on apply() and call() but they seem to be applicable for cases with arguments. How can I achieve a the bind() behavior I need in this situation, using pre-ECMAScript5 methods?
Instead of giving my own answer, John Resig tells you how here. (Click on 1) Our Goal then hit Next).
Resig’s solution is from prototype.js. You can also see MDN’s description here with implementation code as well, approximating the actual ES5 implementation. It should be good enough for most purposes, though.