2013-05-14 25 views
3

我在代碼中遇到了一些問題。那就是:在回調函數中訪問類屬性

// We are in the constructor of my class 
this.socket.emit('getmap', {name: name}, function(data){ 
    this.mapData = data.map; 
    this.load(); 
}); 

的問題是,mapData屬性未設置,其實this指命名空間的Socket。 如何通過此功能訪問this.mapData

而且我的英語不好對不起......

+0

'的this.mapData' :) – palra

+0

可能重複的[事件處理程序調用錯誤的上下文(http://stackoverflow.com/questions/6300817/event-handler-called- with-wrong-context) –

+0

@palra你會將其中一個答案標記爲「正確」嗎? –

回答

7

您需要保存到this對象的引用。在回調函數this內將引用函數已被調用的對象。一個常見的模式是這樣的:

// We are in the constructor of my class 
var self = this; 
this.socket.emit('getmap', {name: name}, function(data){ 
    self.mapData = data.map; 
    self.load(); 
}); 
+0

擊敗我吧! :) –

3

你必須要知道的JavaScript如何確定的this值。在您使用的匿名功能中,它通常是網絡上的全局命名空間或window對象。無論如何,我只是建議你利用閉包並在構造函數中使用一個變量。

// We are in the constructor of my class 
var _this = this; 
this.socket.emit('getmap', {name: name}, function(data){ 
    _this.mapData = data.map; 
    _this.load(); 
}); 
+0

謝謝你解決了這個問題! :D – palra

+0

@palra我推薦在javascript中閱讀'this'關鍵字。例如。 http://devign.me/javascript-this-keyword/。谷歌「JavaScript關鍵字」,你會發現很多解釋。 –