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

4

1 回答 1

2

The problem is not with Chatter.prototype.acknowledge (see http://jsfiddle.net/aEdvh/ )

It's with the way you're calling it.

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

Calls acknowledge with the value of this in the socket callback (see this guide).

You need to bind the value of this to the context. Try using .bind:

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

If you need to support older browsers like IE8, or you don't like bind, you can do so manually as such

   var that = this;
   this.socket.on('acknowledge', function(data){
       that.acknowledge(data);
   });
于 2013-05-21T21:00:19.593 回答