在收到的websocket消息的ES6类中未定义的方法

时间:2018-01-12 12:48:06

标签: javascript websocket ecmascript-6

当websocket事件被触发时,我收到以下消息。无法访问外部上下文对象。

  

未捕获的TypeError:无法读取属性' wsHandler'未定义的       在WebSocket.onmessage_recieved(clsWebSocketSender.js:42)

class WebSocketSender
{
    constructor(wsHandler)
    {
        var _self=this;        
        this.wsHandler=wsHandler;
        this.ws==null;      
        this.url='';
    }

    intialize(url,sender)
    {
        this.url=url;
        this.ws = new WebSocket(url);  
        this.ws.onopen=()=>console.log("opened");    
        this.ws.onclose=()=>console.log("closed");                        
        this.ws.onerror=()=>console.log("error");
        this.ws.addEventListener('message',this.onmessage_recieved);
    }

    send(data)
    {
        if(this.ws.readyState==1)
        {            
            this.ws.send(data);
        }
    }

    onmessage_recieved(e)
    {
        debugger;
        var server_message = e.data;
        let jsonData = JSON.parse(e.data);
        this._self.wsHandler.onMessageReceived(jsonData)
    }

    close()
    {
        if(this.ws.readyState==1)
        {
            this.ws.close();
        }
    }
}

3 个答案:

答案 0 :(得分:2)

使用箭头功能进行回调:将 onmessage_recieved 方法更改为:

onmessage_recieved = (e) => {
    debugger;
    var server_message = e.data;
    let jsonData = JSON.parse(e.data);
    this.wsHandler.onMessageReceived(jsonData)
}

答案 1 :(得分:1)

您正尝试通过_self访问它,这是构造函数的本地变量:

var _self=this;

尝试直接在this上访问它:

this.wsHandler.onMessageReceived(jsonData)

如果您遇到this未定义的问题或者您希望的其他问题(我希望您会这样做),只需更改您的事件监听器以使用箭头功能,这将保留您的{ {1}}。

this

this.ws.addEventListener('message', (message) => this.onmessage_recieved(message));

这里的主要区别是:

class WebSocketSender { constructor(wsHandler) { this.wsHandler = wsHandler; this.ws == null; this.url = ''; } intialize(url, sender) { this.url = url; this.ws = new WebSocket(url); this.ws.onopen = () => console.log("opened"); this.ws.onclose = () => console.log("closed"); this.ws.onerror = () => console.log("error"); this.ws.addEventListener('message', message => this.onmessage_recieved(message)); } send(data) { if (this.ws.readyState == 1) { this.ws.send(data); } } onmessage_recieved(e) { debugger; var server_message = e.data; let jsonData = JSON.parse(e.data); this.wsHandler.onMessageReceived(jsonData) } close() { if (this.ws.readyState == 1) { this.ws.close(); } } }

WebSocket将调用this.ws.addEventListener('message', this.onmessage_recieved);并将其自身传递为onmessage_recieved

this

箭头函数将保留this.ws.addEventListener('message', message => this.onmessage_recieved(message));并忽略WebSocket传递的任何内容this

答案 2 :(得分:0)

在构造函数中更改

this._self.wsHandler.onMessageReceived(jsonData)

this.wsHandler.onMessageReceived(jsonData)

_self变量只会存在于构造函数中,不会出现在其他函数中