是否有任何方法调用函数,但将上下文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()
时所具有的“正常”上下文,而不是全局对象或其他任何东西。否则,有时会把事情弄坏。
发布于 2012-07-18 07:23:03
只需将第一个参数设置为全局对象(即浏览器中的window
)。
在ES3浏览器中,您可以传递null
,它将自动更改为全局对象,但行为已在ES5规范中删除。。
编辑听起来好像你只需要一个新的函数:
EventEmitter.prototype.emitArgs = function(event, args) {
this.emit.apply(this, [event].concat(args));
}
这时,您只需调用:
emitter.emitArgs('event', args);
(编辑多亏了@Esalija for [].concat
)
发布于 2012-07-18 07:23:21
如果您不关心上下文,可以传递null
或undefined
。在函数内部,this
然后将引用全局对象。时处于非严格模式严格模式.
函数的“默认”上下文很难定义。
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));
}
发布于 2014-03-29 08:26:42
这是由本机函数“参数”变量解决的。
var EventEmitter = window.EventEmitter = function(){
//this.emit = this.emit.bind(this);//bind emit to "this"
return this;
};
EventEmitter.prototype.isMe = function(obj){
return obj === this;
};
EventEmitter.prototype.emit = function(eventName){
var input = Array.prototype.slice.call(arguments, 1);
console.log("this:%O, Emitting event:%s, with arguments:%O", this, eventName,input);
};
emitter = new EventEmitter();
emitter.emit('magicEvent', 'Zelda Con', 'Zork Meetup', 'etc');
为了维护“此”上下文,您可以在构造函数中绑定emit方法,尽管这将创建每个实例“属于”的对象属性,增加内存消耗,并且实际上在对象创建时执行所有原型链查找(绑定方法),不管您是否需要它们。
https://stackoverflow.com/questions/11536177
复制相似问题