2013-05-21 2 views
0

그래서 나는이 객체가 있고, 나는 선언하면서 나는 다른 속성을 참조하는 방법 궁금 : this.acknowledge 작품을 호출,선언하는 동안 객체 속성을 참조 하시겠습니까?

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 행에. 누군가 내가 뭘 잘못하고 있다고 말할 수 있습니까?

+0

로 수동으로 할 수있는 방법을'this' 작품에 대해 자세히 알아보기 : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/this. –

+1

5 번 라인에서 실제로 this.acknowledge를 호출하지 않고 콜백으로 전달하여 나중에 호출 할 수 있습니다. – Mathletics

답변

2

이 문제는 (http://jsfiddle.net/aEdvh/ 참조)

그것은 당신이 그것을 호출하는 방식에있어 Chatter.prototype.acknowledge하지입니다.

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

소켓 콜백에서 this의 값 (this guide 참조) acknowledge를 호출합니다.

this 값을 컨텍스트에 바인딩해야합니다. .bind를 사용해보십시오 :

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

당신은 IE8과 같은 이전 버전의 브라우저를 지원해야하거나 바인드 마음에 들지 않으면

, 당신은

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