Is there any method that invokes a function but sets the context this to the “default” value that it has when I invoke the function by doing fn()?
This method should accept an array and pass the single elements as arguments to the function, much like apply() does:
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);
EDIT: To clarify this, I do care about the value that this will have inside the called function – it needs to be the “normal” context it has when doing emitter.emit(), not the global object or anything else. Otherwise, this will break things sometimes.
Just set the first parameter to the global object (i.e.
windowin a browser)In ES3 browsers you could pass
nullinstead and it would be automatically be changed to the global object, but that behaviour has been removed in the ES5 specifications.EDIT it sounds like you just need a new function:
at which point you can just call:
(EDIT thanks to @Esalija for
[].concat)