【发布时间】:2012-07-17 04:21:51
【问题描述】:
是否有任何方法调用函数但将上下文 this 设置为当我通过执行 fn() 调用函数时它具有的“默认”值?
这个方法应该接受一个数组并将单个元素作为参数传递给函数,就像 apply() 所做的那样:
emitter = new EventEmitter();
args = ['foo', 'bar'];
// This is the desired result:
emitter.emit('event', args[0], args[1], ...);
// I can do this using apply, but need to set the context right
emitter.emit.apply(emitter, 'event', args);
// How can I trim the context from this?
emitter.emit.???('event', args);
编辑:为了澄清这一点,我确实关心 this 在被调用函数中的值 - 它必须是它在执行 emitter.emit() 时所具有的“正常”上下文,不是全局对象或其他任何东西。否则,这有时会破坏事情。
【问题讨论】:
-
那么
"normal"上下文是什么? -
-
someObject.emit.apply(someObject, args)那么呢? -
@Esailija 是的,这就是他所追求的 - 他只需要一些语法糖来避免重复(根据我的更新答案)
-
@Esailija 啊,不,不止这些 - 他希望第一个 arg 与其他 arg 分开。
标签: javascript