簡體   English   中英

Javascript SetInterval() scope 問題

[英]Javascript SetInterval() scope problem

我在 javascript 中寫了一個 class ,如下所示:

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

但是在調用 setInterval() 后,'this' 指的是 window。 所以我無法訪問 class 中的變量。 我該如何解決這個 scope 問題?

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

請注意,您的代碼包含在function中。

首先,你的setInterval沒有按照你的想法做。 您正在對document.write(this.n++)結果執行 setInterval 。 寫入立即發生,並且只會觸發一次。

代碼應該是:

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

setInterval 需要一個 function 每n ms 執行一次。 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);
    }
}

你已經聲明了t ,使用它,所有人都是正確的,使用 function 語句,但是要在t中使用n

document.write.... 現在那是老派。 試試document.write(main.n++)嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM