javascript - 如何在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
推荐阅读
- java - google calendar api 说 400 bad request 由于无效值(会议属性)
- node.js - Twilio autopilot whatsapp 使用 nodeJS 发起与电话的对话
- python - Python 线程无法启动
- phoenix-framework - 如何使用 Phoenix LiveView 处理表单文件?
- iis - IIS 10.0 SSI 错误:已为此虚拟路径禁用 #EXEC 调用
- pine-script - 在 Pine Script Tradingview 中使用 Security() 的 EMA 问题
- datetime - Pyspark 通过列表理解从日期时间获取时间属性
- javascript - 如何从此 JSON 创建图表?
- python-3.x - 绘制 Seaborn 情节并添加图例
- python-2.7 - 添加将字典附加到另一个 multiprocessing.managers.DictProxy 中的列表