Preserve 'this' reference in javascript prototype event handler [duplicate]
Solution 1:
I find bind()
being the cleanest solution so far:
this.bar.onclick = this.ClickEvent.bind(this);
BTW the other this
is called that
by convention very often.
Solution 2:
Check out the MDN document on bind
: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind
Using this functionality, you can change the scope (what this
is):
Example.prototype.SetEvent = function(){
this.bar.onclick = this.ClickEvent.bind(this);
};
Be aware, however, that this is a new addition to EMCA and thus may not be supported in all user agents. There is a pollyfill available at the MDN document linked above.