是否有任何方法调用函数,但将上下文this
设置为当我通过执行fn()
来调用函数时所具有的“默认”值?使用array中的参数调用函数 - 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()
时所使用的“正常”上下文,而不是全局对象或其他任何东西。否则,这有时会破坏事物。
那么什么是“正常”的上下文呢? – Esailija 2012-07-18 07:28:10
当我做'emitter.emit()' - 'emitter'时,'this'的值在这种情况下是函数在其他情况下被附加到的对象。 – Niko 2012-07-18 07:31:20
'someObject.emit.apply(someObject,args)'然后呢? – Esailija 2012-07-18 07:38:06