Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在JavaScript中组合函数调用?_Javascript - Fatal编程技术网

如何在JavaScript中组合函数调用?

如何在JavaScript中组合函数调用?,javascript,Javascript,我目前正在开发一个WebSocket。为此,我创建了一个JavaScript类。在这个类中,我有两个方法:subscribe()和bind()。第一个方法订阅一个频道,下一个方法应该监听它 但当我这样调用我的方法时: let socket = new CustomWebSocket(); socket.subscribe("my-channel").bind("my-event", function (response) { console.log(response); }); 我在

我目前正在开发一个WebSocket。为此,我创建了一个JavaScript类。在这个类中,我有两个方法:
subscribe()
bind()
。第一个方法订阅一个频道,下一个方法应该监听它

但当我这样调用我的方法时:

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);
        }
    }
}

我做错了什么?它认为它可以这样工作…

您返回的是
channelName
订阅
。因此,您实际上是在
channelName
上调用
bind


要能够在
subscribe
的返回值上调用
bind
,您需要从
subscribe
返回
self
this
,返回
channelName
订阅
。因此,您实际上是在
channelName
上调用
bind

要能够对
subscribe
的返回值调用
bind
,您需要从
subscribe
socket.subscribe(“我的频道”)返回
self
this
;socket.bind()-您没有流畅的界面。
socket.subscribe(“我的频道”);socket.bind()-您没有流畅的界面。