[英]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.