简体   繁体   English

Javascript SetInterval() scope 问题

[英]Javascript SetInterval() scope problem

I wrote a class in javascript that looks like this:我在 javascript 中写了一个 class ,如下所示:

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.但是在调用 setInterval() 后,'this' 指的是 window。 So i cannot access the variable inside the class.所以我无法访问 class 中的变量。 How can I solve this scope problem?我该如何解决这个 scope 问题?

function main()
{
    this.var1 =0;
    this.clock = function()
    {
        var t = this;
        var n = 1;
        window.setInterval(function(){ document.write(n++); },1000);
    }
}

Notice that your code is wrapped in function .请注意,您的代码包含在function中。

First of all, your setInterval isn't doing what you think.首先,你的setInterval没有按照你的想法做。 You're doing a setInterval on the result of document.write(this.n++) .您正在对document.write(this.n++)结果执行 setInterval 。 The write happens immediately and will only ever fire once.写入立即发生,并且只会触发一次。

Code should be:代码应该是:

setInterval(function(){
    document.write(n++);
}, 1000);

setInterval takes a function to execute every n ms. setInterval 需要一个 function 每n ms 执行一次。 The scope of the function has access to your n variable, so you don't need a this function 的 scope 可以访问您的n变量,因此您不需要this

function main()
{
    this.var1 =0;
    this.clock = function()
    {
        var t = this;
        var n = 1;
        window.setInterval(function(){ document.write( t.n++); },1000);
    }
}

You already declared t , use it, All guys are correct, use the function statement, but to mantain n in the scope use t .你已经声明了t ,使用它,所有人都是正确的,使用 function 语句,但是要在t中使用n

document.write.... now that's old school. document.write.... 现在那是老派。 Try document.write(main.n++) instead?试试document.write(main.n++)吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM