Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserve 'this' reference in javascript prototype event handler [duplicate]

What is the correct way to preserve a this 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){
    this.foo = foo;
    this.bar = bar;
};
Example.prototype.SetEvent = function(){
    this.bar.onclick = this.ClickEvent;
};
Example.prototype.ClickEvent = function(){
    console.log(this.foo); // logs undefined because 'this' is really 'this.bar'
};
like image 920
George Hess Avatar asked Nov 11 '11 21:11

George Hess


People also ask

What does .prototype do in JavaScript?

The prototype is an object that is associated with every functions and objects by default in JavaScript, where function's prototype property is accessible and modifiable and object's prototype property (aka attribute) is not visible. Every function includes prototype object by default.

What is Eventlistener in JavaScript?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.

Why this is undefined in event handler?

The attribute onClick just stores a reference to that function. Whenever a user clicks on the button, that referenced function is called on the global object. So the keyword this is set to undefined in the strict mode.

What does this refer to in JavaScript?

What is this? In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.


2 Answers

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.

like image 167
Tomasz Nurkiewicz Avatar answered Oct 13 '22 00:10

Tomasz Nurkiewicz


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.

like image 24
Chris Baker Avatar answered Oct 13 '22 00:10

Chris Baker