Javascript 在声明期间引用对象属性?

Javascript 在声明期间引用对象属性?,javascript,javascript-objects,Javascript,Javascript Objects,我有这个对象,我想知道在声明时如何引用其他属性: 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.d

我有这个对象,我想知道在声明时如何引用其他属性:

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
有效。有人能告诉我我做错了什么吗?

问题不在于Chatter.prototype.acknowledge(请参阅)

这就是你所说的

this.socket.on('acknowledge', this.acknowledge);
使用套接字回调中的值this调用
acknowledge
(请参阅)

您需要将
this
的值绑定到上下文。尝试使用:

如果您需要支持像IE8这样的旧浏览器,或者您不喜欢bind,您可以手动这样做

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

了解有关
工作原理的详细信息:。在第5行,您实际上并没有调用
此。确认
,您将其作为回调传递,以便稍后调用。
   var that = this;
   this.socket.on('acknowledge', function(data){
       that.acknowledge(data);
   });