2017-06-06 70 views
0

我在編程初學者,我試圖在JavaScript類,我想從超控功能onConnMessage致電boardCastinit功能,但我收到此錯誤信息,請在這個問題上需要幫助。JavaScript類調用函數

boReferenceError: boardCastInit is not defined

websocket.js

class websocket extends webSocketModel { 

constructor() { 
    let server = new Server(); 
    let mongodb = new mongoDB(); 
    super(server.server); 
} 




onConnMessage(message) { 

    let clients = this.clients; 
    boardCastInit(1); 
} 


boardCastInit(data){ 
     console.log(data) 
    } 


} 

module.exports = websocket; 

websocketModel.js

const ws = require('websocket').server; 

class webSocketModel { 

constructor(httpServer) { 
    if(!httpServer) throw 'Null Http Server'; 
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false }); 
    this.websocket.on('request', this.onConnOpen.bind(this)); 
} 


onConnOpen(request) { 
    var connection = request.accept('echo-protocol', request.origin); 
    console.log('Connection Accepted'); 

    connection.on('message', this.onConnMessage); 
    connection.on('close', this.onConnClose); 
} 

onConnMessage(message) { 
    if (message.type === 'utf8') { 
     console.log(message.utf8Data); 
    } else if (message.type == 'binary') { 
     console.log(message.binaryData.length + 'bytes'); 
    } 
} 

onConnClose(reasonCode, description) { 
    console.log('Connection Closed'); 
} 
} 

module.exports = webSocketModel; 

回答

0

只是改變boardCastInit(1)this.boardCastInit(1)

onConnMessage(message) { 

    let clients = this.clients; 
    this.boardCastInit(1); 
} 
+0

,但它仍然會返回一個錯誤類型錯誤:this.boardCastInit不是一個函數 – Ekoar

0

你應該從類調用它參考:

class websocket extends webSocketModel { 

    constructor() { 
     let server = new Server(); 
     let mongodb = new mongoDB(); 
     super(server.server); 
    } 

    onConnMessage(message) { 
     let clients = this.clients; 
     this.boardCastInit(1); 
    } 


    boardCastInit(data){ 
     console.log(data) 
    } 

} 

module.exports = websocket; 
+0

,但它仍然會返回一個錯誤類型錯誤:this.boardCastInit不是一個函數 – Ekoar

0

你錯過了這個(應該this.boardCastInit(1))。

+0

但它仍然返回一個錯誤類型錯誤:this.boardCastInit是不是函數 – Ekoar

+0

不確定,但這是從類內部調用方法的正確方法。你使用哪個節點版本?另外,如果您執行console.log(typeof this.boardCastInit),您會看到什麼? – Don

+0

我改變connection.on('message',this.onConnMessage); ('message',this.onConnMessage.bind(this)); 它工作! – Ekoar

0

這可能是一個有約束力的問題。也許你想使用箭頭功能上,而不是你的onConnMessage方法:

onConnMessage = (message) => { 
 
    let clients = this.clients; 
 
    this.boardCastInit(1); 
 
}

這將確保thiswebsocket類定義了boardCastInit方法。

0

嘗試在這樣的構造函數中綁定boardCastInit()函數。

constructor() { 
    let server = new Server(); 
    let mongodb = new mongoDB(); 
    super(server.server); 
    this.boardCastInit = this.boardCastInit.bind(this); 
} 

然後從this參考調用它。

onConnMessage(message) { 
    let clients = this.clients; 
    this.boardCastInit(1); 
}