首页 > 解决方案 > 如何在onmessage中调用javascript websocket函数?

问题描述

    websocketstart()
    {
        exampleSocket = new WebSocket('ws://127.0.0.1:8000');
        exampleSocket.onopen = function() {
            // alert('handshake successfully established. May send data now...');
            // exampleSocket.send('hello!!!')
        };
        exampleSocket.onmessage = function(event) {
            let result = JSON.parse(event.data);
            if(result.error == false)
            {
                console.log("ERROR : " + result.parent.message);
                alert('error');
                return;
            }
            this.wantcallfunction(); //<---- SCRIPT438: Object doesn't support property or method 'wantcallfunction'
            return;
        };
        exampleSocket.onclose = function() {
            alert('connection closed');
        };
    }

    wantcallfunction()
    {

    }

this.wantcallfunction(); //<---- SCRIPT438: 对象不支持属性或方法'wantcallfunction'

有没有其他方法可以从 onmessage 中调用该函数?

标签: javascriptwebsocket

解决方案


使用箭头函数,以便将上下文保持this为类。

改变

exampleSocket.onmessage = function(event) {
    // `this` is not the class

exampleSocket.onmessage = (event) => {
    // `this` is  the class

推荐阅读