开发者

Javascript SetInterval() scope problem

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 setInter开发者_高级运维val() 'this' refers to window. So i cannot access the variable inside the class. How can I solve this scope problem?


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.


First of all, your setInterval isn't doing what you think. You're doing a setInterval on the result of document.write(this.n++). 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. The scope of the function has access to your n variable, so you don't need a 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.


document.write.... now that's old school. Try document.write(main.n++) instead?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜