我目前正在开发 WebSocket。为此,我创建了一个 JavaScript 类。在这个类中,我有 2 个方法:subscribe()
和 bind()
。第一个方法订阅一个 channel ,下一个方法应该监听它。
但是当我这样调用我的方法时:
let socket = new CustomWebSocket();
socket.subscribe("my-channel").bind("my-event", function (response) {
console.log(response);
});
我在控制台中收到错误消息:
Uncaught TypeError: socket.subscribe(...).bind is not a function
这就是我在 CustomWebSocket
类中编写函数的方式:
subscribe(channelName) {
let self = this;
let subMsg = {
type: "subscribe",
channel: channelName
};
self.ws.send(JSON.stringify(subMsg));
return channelName;
}
bind(eventName, callback) {
let self = this;
self.ws.onmessage = function (event) {
let eventData = JSON.parse(event.data);
if (eventData.type === "channelMessage") {
callback(eventData.payload);
}
}
}
我做错了什么?它以为可以这样工作...
最佳答案
您正在从 subscribe
返回 channelName;
。因此,您实际上是在尝试在 channelName
上调用 bind
。
为了能够在 subscribe
的返回值上调用 bind
,您需要返回 self
或 this
> 来自订阅
。
关于javascript - 如何在 JavaScript 中组合函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60994721/