Javascript SetInterval() 范围问题
我用 javascript 编写了一个类,如下所示:
function main()
{
this.var1 =0;
this.clock = function()
{
var t = this;
var n =1;
window.setInterval(document.write(this.n++),1000);
}
}
但是在调用 setInterval() 后,“this”引用了 window.setInterval() 。所以我无法访问类内的变量。我该如何解决这个范围问题?
I wrote a class in javascript that looks like this:
function main()
{
this.var1 =0;
this.clock = function()
{
var t = this;
var n =1;
window.setInterval(document.write(this.n++),1000);
}
}
But after calling setInterval() 'this' refers to window. So i cannot access the variable inside the class. How can I solve this scope problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请注意,您的代码包装在
function
中。Notice that your code is wrapped in
function
.首先,您的
setInterval
没有按照您的想法进行。您正在对document.write(this.n++)
的结果执行 setInterval。写入会立即发生,并且只会触发一次。代码应该是:
setInterval 接受一个函数每
n
毫秒执行一次。函数的范围可以访问您的n
变量,因此您不需要this
First of all, your
setInterval
isn't doing what you think. You're doing a setInterval on the result ofdocument.write(this.n++)
. The write happens immediately and will only ever fire once.Code should be:
setInterval takes a function to execute every
n
ms. The scope of the function has access to yourn
variable, so you don't need athis
您已经声明了
t
,请使用它!所有的人都是正确的,使用函数语句,但是要在范围内保持n
,请使用t
。You already declared
t
, use it! All guys are correct, use the function statement, but to mantainn
in the scope uset
.document.write...现在那是老派了。尝试使用
document.write(main.n++)
来代替?document.write.... now that's old school. Try
document.write(main.n++)
instead?