gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:01:00 26 4
gpt4 key购买 nike

    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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com