如何在对象内调用方法中的变量?

时间:2013-05-21 14:51:28

标签: javascript oop

我试图在javascript中学习OOP。

我制作了以下代码,该代码应该返回在某个邮件线程中花费的时间:

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似乎返回undefined,从而阻止计时器运行。我在这里做错了什么?

我还在下面的小提琴中对此进行了测试:http://jsfiddle.net/B5vt5/

3 个答案:

答案 0 :(得分:3)

问题是在名为timerCounter的函数范围内,“this”指的是函数本身。这样做:

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

答案 1 :(得分: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
    }
}

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