是否有任何方法調用函數,但將上下文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