2011-02-07 125 views
0

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

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) 
     { 

     } 
    } 
} 
+0

确实this.timelastsend也解析为undefined? – user535617 2011-02-07 14:08:14

回答

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的另一个原因)。


附录: 如果你不主动地从你的净伪类降大量的对象,我会重构的东西如下:

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,但是如果您希望这些属性可以在对象之外进行写入,那么您可以轻松地将它们添加到创建的对象中。