Wednesday, August 22, 2007

Javascript this

One of the most frustrating things about Javascript is its handling of "this," which you first encounter when attaching events to objects, and next when you try to pass member functions to other member functions within an object, and then try to call them from another member function, like in this (contrived) prototype:

...

sayHello: function(text)
{
alert("Hello " + text);
},

handlerFunc: function(myFunc)
{
//call a member function
myFunc('drblast!');
},

doAlert: function()
{
this.handlerFunc(this.sayHello);
}

...

You'd expect to see an alert window with "Hello drblast!" in it, but instead, an error occurs. The reason is that "this" is set to the global "this" object when you call the myFunc function from within handlerFunc(), since the name "myFunc" is not a member of any object, even though it's representing a member function.

To get this to work, you need to set a member variable to the member function you want to call, as follows:

...

handlerFunc: function(myFunc)
{
//call a member function
this.tempFunc = myFunc;
this.tempFunc('drblast!');
},

...

Now this will be set properly, and you'll get an alert window with message as expected.

1 comment:

Anonymous said...

you could also use the methods 'apply' and 'call' on a function to bind it to the this you expect. eg:

handerFunc: function(myFunc)
{
myFunc.call(this, 'drblast!');
}

call takes an object to treat as 'this' followed by varargs as if you were calling it directly, and apply takes a 'this' and an array of arguments