admin管理员组文章数量:1321065
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 badges3 Answers
Reset to default 11setTimeout
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);
本文标签: Javascript literal loses its variables when called with setTimeoutStack Overflow
版权声明:本文标题:Javascript literal loses its variables when called with setTimeout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742023888a2415184.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论