2013-05-21 45 views
0

所以我有這樣的對象,我想知道我如何參照其它特性,同時宣佈:在聲明中引用對象屬性?

var Chatter = function(io){ 
    this.base_url = "http://chat.chatter.com:1337"; 
    this.debug_on = true; 
    this.socket = io.connect(this.base_url); 
    this.socket.on('acknowledge', this.acknowledge); 
} 
Chatter.prototype.debug = function(msg){ 
    if(this.debug_on){ 
     var m = {timestamp:Date.create().format('{yyyy}-{MM}-{dd} {24hr}:{mm}:{ss}{tt}'), message:msg}; 
     console.debug('#[ chatter DEBUG ]# - {timestamp} - {message}'.assign(m)); 
    } 
} 
Chatter.prototype.acknowledge = function(data){ 
    this.debug('Acknowledgement received!'); //This throws an error, claims #debug is not there 
    this.uuid = data.uuid; 
}; 

調用this.debug()失敗,但在第5行,調用this.acknowledge作品。有人能告訴我我做錯了什麼嗎?

+0

瞭解更多有關如何'this'作品:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this。 –

+1

在第5行中,你實際上並沒有調用'this.acknowledge',而是將它作爲一個回調傳遞給稍後調用。 – Mathletics

回答

2

的問題不在於Chatter.prototype.acknowledge(見http://jsfiddle.net/aEdvh/

這是一個與你打電話的方式。

this.socket.on('acknowledge', this.acknowledge); 

調用acknowledgethis插座回調(見this guide)的值。

您需要將this的值綁定到上下文。嘗試使用.bind

this.socket.on('acknowledge', this.acknowledge.bind(this)); 

如果您需要支持舊的瀏覽器IE8一樣,或者你不喜歡綁定,您可以手動這樣

var that = this; 
    this.socket.on('acknowledge', function(data){ 
     that.acknowledge(data); 
    });