如何javascript websocket调用onmessage中的函数?

sti*_*tin 1 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()
    {

    }
Run Code Online (Sandbox Code Playgroud)

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

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

cha*_*tfl 7

使用箭头函数可以保持上下文this类的上下文。

改变

exampleSocket.onmessage = function(event) {
    // `this` is not the class
Run Code Online (Sandbox Code Playgroud)

exampleSocket.onmessage = (event) => {
    // `this` is  the class
Run Code Online (Sandbox Code Playgroud)