2013-05-21 96 views
1

我正在尝试在JavaScript中学习OOP。如何从对象内部调用方法中的变量?

我作了如下的代码应该返回在一定mailthread所花费的时间:

function mailThread(url) { 
    this.timerIsOn = true; 
    this.c = 0; 
    this.url = url; 
    this.timerCounter = function() { 
     if(this.timerIsOn) { //doesnt get called?? 
      console.log('timerison'); 
      this.c = this.c + 1; 
      console.log(this.c); 
     } else { 
      this.windowTimeOpen = this.c 
     } 
    } 
    this.timerInterval = setInterval(this.timerCounter, 1000); 
} 

mailThread1 = new mailThread('test'); 

然而this.timerIsOn似乎返回未定义从而防止计时器运行。我在这里做错了什么?

而且我在下面的测试拨弄此:http://jsfiddle.net/B5vt5/

+1

在你的小提琴,你为什么有'alersdsdt(this.timerIsOn);'? – Ian

+0

抱歉没有保存:S现在应该消失 – Bunker

+1

问题在于,当您将函数引用传递给'setInterval'时,'this'的值会发生变化。如果你在函数的顶部声明'var self = this;'并且不断使用'self'而不是'this',它应该可以工作:http://jsfiddle.net/B5vt5/2/ – Ian

回答

3

的问题是,所谓的timerCounter功能的范围内,“这”指的是函数本身。这样做:

function mailThread(url) { 
    var self = this; 
    self.timerIsOn = true; 
    self.c = 0; 
    self.url = url; 
    self.timerCounter = function() { 
    if (self.timerIsOn) { //Using self instead of this 
     console.log('timerison'); 
     self.c=this.c+1; 
     console.log(self.c); 
    } else { 
    self.windowTimeOpen = self.c 
    } 
    } 
    self.timerInterval = setInterval(self.timerCounter,1000); 
} 

mailThread1 = new mailThread('test'); 

我建议你看一下MDN introduction to OOP

2

this是不是你给setTimeout回调的对象,但全局对象(window)。解决办法是将其保存在一个变量中:

var _this = this; 
this.timerCounter = function() { 
    if (_this.timerIsOn) { 
     console.log('timerison'); 
     _this.c++; 
     console.log(_this.c); 
    } else { 
     _this.windowTimeOpen = _this.c 
    } 
} 
1

this.timerCounter是一个函数。当它从setTimeout中调用时,它的上下文被赋予window,所以this不是你认为的那样。

您或者需要使用.bindthis设置为您想要的值。

this.timerInterval = setInterval(this.timerCounter.bind(this),1000); 

或者保存this到一个变量:

var that = this; 
this.timerCounter = function() { 
    if (that.timerIsOn) { 
     // use that instead of this 
    } 
} 

this.timerInterval = setInterval(this.timerCounter,1000); 
相关问题