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.

3 comments:

adam said...

Hello I just entered before I have to leave to the airport, it's been very nice to meet you, if you want here is the site I told you about where I type some stuff and make good money (I work from home): here it is

Brehaut 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

web said...

There is a lot of competition in outsourcing software development, as there are many firms across the globe catering to clients looking for outsourcing their work. What is good is that the takers can choose the best from the lot. http://www.infysolutions.com.