this.connection的JavaScript范围问题

时间:2011-02-07 14:06:28

标签: javascript scope

我有以下JavaScript代码。在函数更新中,this.connection解析为undefined而不是数字。我做错了什么?

function Net()
{
    this.connection = -1;    
    this.counter = 1;
    this.timelastsend = -1;
    setInterval( this.update, 3000);
}

Net.prototype.update = function()
{          
    if (this.connection > 0 && this.timelastsend > 0)
    {
        var now = new Date().valueOf();        
        if (now - this.timelastsend > 1000 * 60)
        {

        }
    }
}

1 个答案:

答案 0 :(得分:6)

使用this的一个问题是this取决于您调用函数的方式。

setInterval会将您的update方法称为独立函数,因此this将设置为全局对象。

如果您确实需要使用this功能,请按以下步骤重写对setInterval的调用:

function Net() {
    var self = this;
    this.connection = -1;    
    this.counter = 1;
    this.timelastsend = -1;
    setInterval( function () { self.update() }, 3000);
}

通过这种方式,您将创建一个self变量,该变量将继续引用您的对象(如果您使用new运算符创建了它 - 另一个原因是避免this)。


<强>附录: 如果你没有从你的Net伪类中主动下降很多对象,我会按如下方式重构:

function createNet() {
    var connection = -1,
        counter = -1,
        timelastsent = -1,
        self,
        update;

    update = function () {
        var now;
        if (connection > 0 && timelastsent > 0) {
            now = new Date().valueOf();
            if (now - timelastsent > 1000 * 60) {

                // ... update code ...

                counter += 1;
                timelastsent = now;
            }
        }
    };

    setInterval(update, 3000);

    return {
        update: update,
        getTimeLastSent: function () { return timelastsent; },
        getCounter: function () { return counter; },
        getConnection: function () { return connection; }
    };
}

你会发现在任何地方都没有提到this,这意味着没有歧义。我为连接,计数器和timelastsent属性添加了三个getter,但是如果你想让它们可以从对象外部写入,你就可以轻松地将它们添加到创建的对象中。