我是编程的初学者,我正在尝试javascript类,我想从覆盖函数 onConnMessage 中调用 boardCastinit 函数,但是我收到此错误消息,请帮助解决这个问题。
boReferenceError:boardCastInit未定义
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 :(得分:0)
只需将boardCastInit(1)
更改为this.boardCastInit(1)
onConnMessage(message) {
let clients = this.clients;
this.boardCastInit(1);
}
答案 1 :(得分:0)
您应该从课程this
引用中调用它:
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;
答案 2 :(得分:0)
你错过了这个(应该是this.boardCastInit(1))。
答案 3 :(得分:0)
这可能是一个具有约束力的问题。也许您想在onConnMessage
方法上使用箭头功能:
onConnMessage = (message) => {
let clients = this.clients;
this.boardCastInit(1);
}
这将确保this
引用定义了websocket
方法的boardCastInit
类。
答案 4 :(得分: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);
}