javascript - 如何javascript websocket调用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 中调用该函数?

最佳答案

使用箭头函数,这样您就可以将 this 的上下文作为类。

改变

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

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

关于javascript - 如何javascript websocket调用onmessage中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385408/

相关文章:

javascript - AngularJS $promise 与 NgResource 一起使用

java - Tomcat 8.0.x Websockets、SSL 和 Windows --> 最后一帧延迟

node.js - 在 Symfony2 应用程序中包含 Node.JS + Socket.IO

node.js - 获取 Kue 作业的结果并通过开放连接将其推送给客户端

javascript - JavaScript 递归函数问题

javascript - 如何选择由 jQuery 生成的元素?

php - 使用循环从 POST 设置变量和字符串

javascript - 从 Weather API 中提取数据并在推特上发布

java - Spring Security 和 Websockets - 未为框架处理程序设置身份验证

Node.js、WebSocket 位置问题?