是否有任何方法可以调用函数但设置上下文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);
EDIT:为了澄清这一点,我确实关心this
将在被调用函数内部 - 它需要是执行时所具有的“正常”上下文emitter.emit()
,而不是全局对象或其他任何东西。否则,这有时会破坏事情。
你可以通过null
or undefined
如果你不关心上下文。在函数内部,this
然后将引用全局对象当处于非严格模式时and to null分别undefined在严格模式下.
函数的“默认”上下文很难定义
function f() { return this };
a = { b: f }
c = a.b;
console.log(f()); # window
console.log(a.b()); # a
console.log(c()); # window
其中哪一项是“正确”的上下文?
在你的情况下,你可能会考虑一个效用函数
/* you might call it something else */
emitter.emit_all = function (event, args) {
return this.emit.apply(this, [event].concat(args));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)