views:

306

answers:

3

Hi,

I have this piece of code, and it doesn't work as I expect (it's demo code, distilled from a larger program):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Test</title>

<script language="javascript" type="text/javascript">
var test = {
 variable: true,
 go: function() {
  alert(this.variable);
 }
};

function s() {
 test.go();
 setTimeout(test.go, 500);
}

</script>

</head>
<body>
<form action="#">
<input type="button" value="Go" onclick="s();" />
</form>
</body>
</html>

When I click the Go button, both in IE and FF (the only browsers I care about atm), the first alert box shows "true", the second one "undefined".

My questions are why, and how can I avoid it?

+2  A: 

It looks like "this" points to something else when you call "go" from the timeout. it probably points to window.

try something like this

var fn = function(){
    test.go.apply(test, []);
}
setTimetout(fn, 500);
mkoryak
Thanks, your answer was first, but the others are shorter, so I accepted one of them.
Tominator
+3  A: 

change the line

setTimeout(test.go, 500);

with

setTimeout(function(){test.go()}, 500);

and your script shoud work fine.

Eineki
+8  A: 

setTimeout will execute the passed function in the context of the window, so 'this' refers to the window. Try this instead:

setTimeout(function(){
    test.go();
}, 500);
J-P