2012-06-26 55 views
0

我已經在我的this.current_test = null;函數的頂部聲明一個變量,然後下了線我有一個setInterval函數,我需要的變量設置爲一個新的參數...setInterval的變量的作用域

this.current_test.failed = true;

代碼:

timer = this.window.setInterval(function() 
    { 
     this.window.clearInterval(timer); 
     this.current_test.failed = true; 
    },1000); 
} 

但是我得到一個錯誤TypeError: 'undefined' is not an object (evaluating 'this.current_test.failed = true'

而且我認爲這是是因爲this.current_test沒有在setInterval函數內部定義,所以我該如何編輯該變量?

+0

您可以發佈更多代碼嗎?具體來說就是您定義'current_test'的部分。 –

回答

0

定時器函數中'this'的作用域不會引用this.window。這個範圍是,對功能唯一可以做的

var wnd=this.window; // take your widow to local variable 
timer = this.window.setInterval(function() 
{ 
    this.window.clearInterval(timer); 
    wnd.current_test.failed = true; // use your local variabe in the function 
    },1000); 
} 

順便說什麼reffering到窗口爲什麼你需要「這個」,也是如果cuurent_test是一個全局變量,那麼你可以聲明像

var current_test; 

並且您可以使用定時器功能內的全局變量