最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript literal loses its variables when called with setTimeout - Stack Overflow

programmeradmin5浏览0评论

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" ".dtd">
<html xmlns="" >
<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?

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/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3/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?

Share Improve this question edited May 31, 2015 at 16:37 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Jun 9, 2009 at 15:14 TominatorTominator 1,2243 gold badges20 silver badges37 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

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

change the line

setTimeout(test.go, 500);

with

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

and your script shoud work fine.

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);
发布评论