我正在尝试在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/
在你的小提琴,你为什么有'alersdsdt(this.timerIsOn);'? – Ian
抱歉没有保存:S现在应该消失 – Bunker
问题在于,当您将函数引用传递给'setInterval'时,'this'的值会发生变化。如果你在函数的顶部声明'var self = this;'并且不断使用'self'而不是'this',它应该可以工作:http://jsfiddle.net/B5vt5/2/ – Ian