在一些Javascript代码(具体是node.js)中,我需要使用一组未知的参数调用函数而不更改上下文.例如:
function fn() {
var args = Array.prototype.slice.call(arguments);
otherFn.apply(this, args);
}
Run Code Online (Sandbox Code Playgroud)
上面的问题是,当我调用时apply,我通过传递this第一个参数来改变上下文.我想传递args给被调用的函数而不改变被调用函数的上下文.我基本上想要这样做:
function fn() {
var args = Array.prototype.slice.call(arguments);
otherFn.apply(<otherFn's original context>, args);
}
Run Code Online (Sandbox Code Playgroud)
编辑:添加有关我特定问题的更多详细信息.我正在创建一个Client类,其中包含一个socket(socket.io)对象以及与连接有关的其他信息.我通过客户端对象本身公开套接字的事件监听器.
class Client
constructor: (socket) ->
@socket = socket
@avatar = socket.handshake.avatar
@listeners = {}
addListener: (name, handler) ->
@listeners[name] ||= {}
@listeners[name][handler.clientListenerId] = wrapper = =>
# append client object as the first argument before passing to handler
args = Array.prototype.slice.call(arguments)
args.unshift(this)
handler.apply(this, args) # <---- …Run Code Online (Sandbox Code Playgroud)