javascript - Referring to object properties during declaration? -
so have object, , wondering how refer other properties while declaring:
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 error, claims #debug not there this.uuid = data.uuid; }; calling this.debug() fails on line 5, calling this.acknowledge works. can tell me doing wrong?
the problem not chatter.prototype.acknowledge (see http://jsfiddle.net/aedvh/ )
it's way you're calling it.
this.socket.on('acknowledge', this.acknowledge); calls acknowledge value of this in socket callback (see this guide).
you need bind value of this context. try using .bind:
this.socket.on('acknowledge', this.acknowledge.bind(this)); if need support older browsers ie8, or don't bind, can manually such
var = this; this.socket.on('acknowledge', function(data){ that.acknowledge(data); });
Comments
Post a Comment