如何在JavaScript的类回调中读取已修改的类属性?
如何在JavaScript的类回调中读取已修改的类属性?
我看了你的代码,问题核心出在WSS类里connection回调函数的this指向错误!
你在this.wss.on('connection', function connection(ws) { ... })中使用了普通函数作为回调,这个函数里的this并不是指向WSS类的实例,而是指向WebSocket.Server对象(非严格模式下可能是全局对象)。所以你在回调里给this.activeWs赋值时,根本没修改到WSS实例的activeWs属性,导致后续调用sendCommand时,实例的activeWs始终是初始的null。
下面给你三种可行的解决办法:
方法1:使用箭头函数(最推荐)
箭头函数不会绑定自己的this,它会继承外层作用域的this,也就是WSS类的实例。修改后的connection回调如下:
this.wss.on('connection', (ws) => { console.log("Client Connected"); if (this.activeWs != null) { this.activeWs.close(1000, "Server initiated close"); console.log("Closed old session") } this.activeWs = ws; })
方法2:提前保存this的引用
在回调外部先把WSS实例的this存到一个变量(比如self)里,然后在回调中用这个变量访问实例属性:
const self = this; this.wss.on('connection', function connection(ws) { console.log("Client Connected"); if (self.activeWs != null) { self.activeWs.close(1000, "Server initiated close"); console.log("Closed old session") } self.activeWs = ws; })
方法3:用bind绑定this
通过bind方法把回调函数的this强制绑定到WSS实例上:
this.wss.on('connection', function connection(ws) { console.log("Client Connected"); if (this.activeWs != null) { this.activeWs.close(1000, "Server initiated close"); console.log("Closed old session") } this.activeWs = ws; }.bind(this))
另外,我注意到你的sendCommand方法只做了打印,没有真正发送数据给客户端,建议补充发送逻辑:
this.sendCommand = (data) => { console.log(this.activeWs) if (this.activeWs == null) { return; } console.log(data); this.activeWs.send(data); // 新增这行实现数据发送 }
最后附上修改后的完整代码(箭头函数版本):
class WSS { constructor(){ const WebSocket = require('ws'); this.wss = new WebSocket.Server({ port: 3001}); this.activeWs = null; this.wss.on('connection', (ws) => { console.log("Client Connected"); if (this.activeWs != null) { this.activeWs.close(1000, "Server initiated close"); console.log("Closed old session") } this.activeWs = ws; }) this.sendCommand = (data) => { console.log(this.activeWs) if (this.activeWs == null) { return; } console.log(data); this.activeWs.send(data); } } } class WS { constructor(clientId, onmessage) { this.clientId = clientId; const WebSocket = require('ws'); this.ws = new WebSocket('ws://localhost:8080'); // 补充ws://协议前缀,避免连接失败 this.ws.onmessage = (event) => { onmessage(event)}; } } const serverWSS = new WSS(); const listener = new WS("000", forwardMessage) function forwardMessage(event) { serverWSS.sendCommand(event.data); }
备注:内容来源于stack exchange,提问作者servvs
相关产品推荐
相关产品推荐

