[英]How can I combine function calls in JavaScript?
I'm currently developing a WebSocket.我目前正在开发一个 WebSocket。 For that purpose I've created a JavaScript class.为此,我创建了一个 JavaScript 类。 In this class I've 2 methods: subscribe()
and bind()
.在这个类中,我有 2 个方法: subscribe()
和bind()
。 The first method subscribes to a channel and the next one should listen to it.第一种方法订阅一个频道,下一个方法应该收听它。
But when I call my methods this way:但是当我这样调用我的方法时:
let socket = new CustomWebSocket();
socket.subscribe("my-channel").bind("my-event", function (response) {
console.log(response);
});
I'm getting an error message in my console:我在控制台中收到一条错误消息:
Uncaught TypeError: socket.subscribe(...).bind is not a function
This is how I wrote my functions inside my CustomWebSocket
class:这就是我在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);
}
}
}
What did I wrong?我做错了什么? It thought it can work this way...它认为它可以这样工作......
You're returning channelName;
您正在返回channelName;
from subscribe
.从subscribe
。 So you're effectively trying to call bind
on channelName
.因此,您实际上是在尝试在channelName
上调用bind
。
To be able to call bind
on the return value of subscribe
, you need to return self
or this
from subscribe
.为了能够对subscribe
的返回值调用bind
,您需要从subscribe
返回self
或this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.