...

View Full Version : Problem with 'this'



gorilla
02-02-2007, 02:01 PM
Hi!


obj=new Object()
obj.prop='hello'
obj.func=function()
{
alert(this.prop)
setTimeout(this.func,10)
}
obj.func()

I think this should keep alerting 'hello' but for some reason it doesn't. Can you help me out with this?
Thank you!

liorean
02-02-2007, 02:49 PM
this comes from the object part of object.member(). If you move a function from object to anotherObject, and call anotherObject.member() then the value of this will be anotherObject.

In this case, you're not calling the function yourself, however. setTimeout calls it for you. But you handed setTimeout the function object itself, which has no binding to the this object. So, the this object will be the global object instead, like all normal function calls. Is there a way to solve this? Of course.


var
obj={
prop:'hello',
func:function(){
var
me=this;
alert(this.prop);
setTimeout(function(){me.func()},10);
}};
obj.func();

gorilla
02-02-2007, 02:58 PM
I see it now!
:thumbsup: Thanks!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum