2011-02-07 122 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,但是如果您希望這些屬性可以在對象之外進行寫入,那麼您可以輕鬆地將它們添加到創建的對象中。