Tominator
Tominator

Reputation: 1224

Javascript literal loses its variables when called with setTimeout

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">
<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?

Upvotes: 2

Views: 517

Answers (3)

mkoryak
mkoryak

Reputation: 57958

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);

Upvotes: 2

James
James

Reputation: 111920

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);

Upvotes: 11

Eineki
Eineki

Reputation: 14909

change the line

setTimeout(test.go, 500);

with

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

and your script shoud work fine.

Upvotes: 4

Related Questions