2012-08-07 60 views
3

我正在使用John Resig的Simple JavaScript Inheritance,並遇到一個問題,我失去了'this'引用的內容。使用此代碼:Javascript繼承和丟失'this'的上下文

var Runner = Class.extend({ 
init: function() { 
    this.update(); 
    if(!this.interval) { 
    this.interval = setInterval(this.update, this.period * 1000); 
    } 
}, 
stop: function() { 
    clearInterval(this.interval); 
}, 
update: function() { 
    this.success() 
}, 
success: function(){ 
} 
}); 

var SubRunner = Runner.extend({ 
update: function() { 
    this._super(); 
}, 
success: function(){ 
    alert('sub runner success'); 
} 
}); 

運行p = new SubRunner()作品我希望和警報sub runner success第一次。第一次運行後,嘗試在錯誤的「this」(窗口)上運行成功函數。

我知道Prototype爲您提供了一個綁定函數,以便您可以將上下文傳遞給該函數,但我在此處做類似的事情時沒有任何運氣。有沒有人有一個起點來弄清楚這一點?

謝謝!

+0

它看起來像我忽略了setTimeout,並且過於強烈地關注成功函數。感謝或幫助大家! – 2012-08-07 21:06:40

回答

3

問題是當您將this.update傳遞給setInterval函數時。在Javascript中,「this」取決於你是否使用點符號調用函數,並且如果將函數作爲回調函數傳遞或將它們存儲在變量中,函數將不會記住它們來自哪裏。

您可以添加一個包裝函數

var that = this; 
setTimeout(function(){ that.update() }, this.perios*1000) 

,或者您可以使用,如果其提供的綁定方法在你的瀏覽器(或者你可以在原型使用類似的功能)。

setTimeout(this.update.bind(this), this.period*1000) 
1

當您將this.update傳遞給setInterval時,將失去上下文。 最簡單的辦法是做

var that = this; 
this.interval = setInterval(function() { that.update() }, this.period * 1000); 
1
this.interval = setInterval(this.update, this.period * 1000); 

setTimeout調用它調用它在全球範圍內(它設置thiswindow)的功能。

您需要傳遞一個函數,調用this.update

var self = this; 
this.interval = setInterval(function(){ 
    self.update(); 
}, this.period * 1000);