this.connection的JavaScript范围问题

cla*_*amp 0 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)
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ijn 6

对使用的问题thisthis取决于你调用函数的方式.

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

如果您确实需要使用该this功能,请将调用重写为setInterval,如下所示:

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

这样,您将创建一个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; }
    };
}
Run Code Online (Sandbox Code Playgroud)

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