2017-06-06 71 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); 
}