setInterval变量范围

时间:2012-06-26 03:40:21

标签: javascript

我在我的函数顶部声明了一个变量this.current_test = null;,然后在我的行中有一个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函数中定义,所以如何编辑该变量呢?

1 个答案:

答案 0 :(得分: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);
}

顺便说一下,为什么你需要'这个'以及if cuurent_test是一个全局变量然后你可以声明像

var current_test;

您可以在计时器功能

中使用全局变量
相关问题