A solution to broken 'this' when using methods as handlers in JavaScript OO

Perhaps you've already run into the problem that 'this' does not refer to the instance the method belongs to when one tries to use a method in an object outside the context of the object, like as an event handler. To take an example using JQuery:

function myClass(){
this.myvar="Hello";
this.myfunc=function(){
alert(this.myvar);
}
}
var obj=new myClass();
$(document).ready(obj.myfunc);

The code would not work as 'this' inside event handlers in JQuery always refers to the HTML element that fired the event. An easy way of solving this is to take advantage of closures, that is, the fact that a function retains its execution context. In other words, a variable defined outside the function is accessible even if the function is called outside its original context, via a reference. Amend the above script as follows:

function myClass(){
var me=this;
this.myvar="Hello";
this.myfunc=function(){
alert(me.myvar);
}
}
var obj=new myClass();
$(document).ready(obj.myfunc);

This would work as expected. During instantiation, the variable 'me' becomes a reference to the object being defined. As it is in the execution context of myClass::myfunc, it remains accessible, and thus the current object can be reached from within the function even without using 'this'.

Popular Posts