-
Website
http://justin.harmonize.fm/ -
Original page
http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/ -
Subscribe
All Comments -
Community
-
Top Commenters
-
maacl
1 comment · 2 points
-
davezor
1 comment · 1 points
-
aaronasjones
1 comment · 1 points
-
mebaran
1 comment · 1 points
-
miami web designer
1 comment · 1 points
-
-
Popular Threads
setTimeout(30, myHotDog.getCondiments);
Where do you get that strange setTimeout? To call myHotDog.getCondiments in 30 seconds, this is the way to go:
setTimeout(myHotDog.getCondiments, 30 * 1000);
Also, the following works just fine for me, in various browsers (IE7/8, FF)? No errors on the console and it happily alerts after 3 seconds.
function HotDog() {
this.condiments = "mustard, ketchup";
this.getCondiments = function() {
alert(1);
return this.condiments;
}
}
var myHotDog = new HotDog();
setTimeout(myHotDog.getCondiments, 3000);
The scope of the timeout-callback will be the same as where it was called.
try this:
for(var i=0;i<3;i++)
{
setTimeout(alert(i), 500); //Will write 3, 3 times because i is 3 when alert is called
}
vs
for(var i=0;i<3;i++)
{
var a = i;
setTimeout(a, 500); //Will write 0, 1, 2 because a is only within the scope of the current iteration
}
Google closures for more info
Defining variable 'a' with a 'var' statement inside the loop is just misleading. JavaScript is not Java.
So the two version do the same.
Also you didn't test your code at all.. Else you would have seen that alert is not called by setTimeOut but instead inside the loop.
You should have written this:
setTimeout(function { alert(i) }, 500);
var my = this;
Is such a beautiful fix, I'm amazed by its simplicity. Cheers!
RT
www.total-privacy.net.tc
1) setTimeout(myObj.myFunc, 1000) - this set to global window object
2) setTimeout(function() { myObj.myFunc() }, 1000) - this set to myObj as we want it.
But you can also pass a string to setTimeout and basically setTimeout() becomes a sort of eval:
3) setTimeout('myObj.myFunc()', 1000) - this set to myObj
Number 2 is the best way to go though.