George Hess George Hess - 1 year ago 134
Javascript Question

Preserve 'this' reference in javascript prototype event handler

What is the correct way to preserve a

javascript reference in an event handler stored inside the object's prototype? I'd like to stay away from creating temp vars like '_this' or 'that' and I can't use a framework like jQuery. I saw a lot of people talk about using a 'bind' function but was unsure of how to implement it in my given scenario.

var Example = function(foo,bar){ = foo; = bar;
Example.prototype.SetEvent = function(){ = this.ClickEvent;
Example.prototype.ClickEvent = function(){
console.log(; // logs undefined because 'this' is really ''

Answer Source

I find bind() being the cleanest solution so far: = this.ClickEvent.bind(this);

BTW the other this is called that by convention very often.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download