2017-12-08 2 views
1

nodejs & socket.io 게임에 대한 간단한 클래스 (래퍼)를 만들려고합니다.TypeError : this.sendHandshake가 함수가 아닙니다.

module.exports = class client { 
constructor(socket) { 
    this.socket = socket; 
    this.createEvents(); 
} 

createEvents() { 
    console.log('creating events'); 
    this.socket.on('handshake', this.onHandshake); 
    this.socket.on('disconnect', this.onDisconnect); 
} 

sendHandshake() { // <------------ sendHandshake is there? 
    console.log('sending handshake'); 
    this.socket.emit('handshake'); 
} 

onHandshake() { 
    console.log('handshake received'); 
    this.sendHandshake(); // <----- TypeError: this.sendHandshake is not a function 
} 

onDisconnect() { 
    console.log('client disconnected'); 
} 
} 

그것은 나에게이 출력

creating events 
handshake received 
sending handshake 

을 제공해야하지만, 대신 나에게 당신이 함수를 전달하는 경우

creating events 
handshake received 
TypeError: this.sendHandshake is not a function 

답변

0

가 자동으로 소유하는 개체에 바인딩되지 않은이 오류를 제공합니다 기능. 더 간단한 예는 다음과 같습니다

const EventEmitter = require('events'); 
class client { 
    constructor() { 
     this.ev = new EventEmitter; 
     this.ev.on('handshake', this.onHandshake); 
     this.ev.emit('handshake'); 
    } 

    onHandshake() { 
     console.log(this); // EventEmitter 
    } 
} 

가 대신 그냥 this.onHandshake.bind(this) 또는 () => this.onHandshake()를 사용하여 당신은 아주 쉽게 할 수 client의 기능을 결합해야합니다. 전자는 명시 적으로 this을 바인딩합니다. 후자는 어휘 적으로 this을 묶습니다. 즉, 정의 된 함수에 this이 무엇이든간에 말입니다. 그 의도 또는 필요한 확실하지 않은 경우 -


나는 또한 당신이 handshake을 방출하여 handshake에 응답 것을 지적합니다.

관련 문제