代码之家  ›  专栏  ›  技术社区  ›  servvs

如何从javascript中的另一个类回调读取修改后的类属性?

  •  0
  • servvs  · 技术社区  · 5 月前

    我有两门关于websockets的课。它们应该用于通过程序作为中介将信息从一个发送到另一个。WSS会监听,并且只能有一个连接。我与另一台服务器建立了客户端连接。在我的主函数中,我实例化了这些对象中的每一个,并将forwardMessage(event)作为回调(onmessage)分配给监听器。它本质上应该转发内容,但问题是,即使在客户端连接到serverWSS对象后,回调也总是将activeWS报告为null。我不确定如何通过这种方式在两者之间找到参考。

    class WSS {
        constructor(){
            const WebSocket = require('ws');
            this.wss = new WebSocket.Server({ port: 3001});
            this.activeWs = null;
    
            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;
            })
    
            this.sendCommand = (data) => {
                console.log(this.activeWs)
                if (this.activeWs == null) {
                    return;
                }
                console.log(data);
            }
        }
    }
    
    class WS {
        constructor(clientId, onmessage) {
            this.clientId = clientId;
            const WebSocket = require('ws');
            this.ws = new WebSocket('localhost:8080');
            this.ws.onmessage = (event) => { onmessage(event)};
        }
    }
    
    serverWSS = new WSS();
    listener = new WS("000", forwardMessage)
    
    function forwardMessage(event) {
        serverWSS.sendCommand(event.data);
    }
    
    1 回复  |  直到 5 月前
        1
  •  1
  •   user29455873    5 月前

    听众的背景 connection 功能与 WSS 类因此行。。。

    this.activeWs = ws;
    

    …初始化一个不同的 activeWs 变量比线。。。

    this.activeWs = null;
    

    一种修复方法是更改WSS类构造函数的代码以定义 context 变量初始化为 this ...

    var context = this;
    

    …并使用 上下文 代码片段中的变量 连接 听众功能和 sendCommand lambda函数,顺便说一句,它可以访问不同的 该上下文 WSS 构造函数,因为它是一个lambda函数而不是函数。。。

    class WSS {
        constructor(){
            const WebSocket = require('ws');
            this.wss = new WebSocket.Server({ port: 3001});
            this.activeWs = null;
    
            var context = this;
    
            this.wss.on('connection', function connection(ws) {
                console.log("Client Connected");
                if (context.activeWs != null) {
                    context.activeWs.close(1000, "Server initiated close");
                    console.log("Closed old session")
                }
                context.activeWs = ws;
            })
    
            this.sendCommand = (data) => {
                console.log(context.activeWs)
                if (context.activeWs == null) {
                    return;
                }
                console.log(data);
            }
        }
    }