使用原始上下文调用具有未知数量参数的Javascript函数

Jos*_*ton 6 javascript functional-programming

我目前正在使用Function.apply来调用具有动态数量的参数的函数,但是我无法访问原始上下文,并且不希望自己设置上下文.我想要的是能够调用具有可变数量的参数的函数,保持原始上下文.

也许一些代码应该告诉你我正在尝试做什么:

function MulticastDelegate() {
    var handlers = [];

    this.event = {
        subscribe: function(handler) {
            if (typeof(handler) === 'function') {
                handlers.push(handler);
            }
        },
        unsubscribe: function(handler) {
            if (typeof(handler) === 'function') {
                handlers.splice(handlers.indexOf(handler),1);
            }
        }
    }

    this.execute = function() {
        var args = Array.prototype.slice.call(arguments);
        for (var handler in handlers) {
            // call this with the original context of the handler
            handlers[handler].apply(null, args);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

本质上,我想要的行为apply- 能够传递一个参数数组 - 没有行为call- 改变函数执行的上下文.

Dan*_*man 5

没有函数的"原始上下文"这样的东西.你必须做这样的事情:

subscribe: function(handler, context) {
    if (typeof(handler) === 'function') {
        handlers.push([handler, context]);
    }
},
Run Code Online (Sandbox Code Playgroud)

然后,当然,

handlers[handler][0].apply(handlers[handler][1], args);
Run Code Online (Sandbox Code Playgroud)

或者(这就是我要做的),将它留给调用者以确保处理程序具有正确的上下文.例如,而不是delegate.subscribe(this.foo)

var self = this
delegate.subscribe(function () { self.foo() })
Run Code Online (Sandbox Code Playgroud)

或者,使用Function.prototype.bind,

delegate.subscribe(this.foo.bind(this))
Run Code Online (Sandbox Code Playgroud)