使用数组中的参数调用函数 - apply()而不使用上下文参数? [英] Call function with parameters from array - apply() without the context parameter?

查看:114
本文介绍了使用数组中的参数调用函数 - apply()而不使用上下文参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法调用函数但将上下文设置为当我通过执行 fn()?

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()?

这个方法应该接受一个数组并将单个元素作为参数传递给函数,就像apply()一样:

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);

编辑:为了澄清这一点,我确实关心这个将包含在被调用函数内部 - 它需要是执行 emitter.emit(),而不是全局对象或其他任何东西。否则,这有时会破坏。

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. window in a browser)

在ES3浏览器中,您可以传递 null 而不是它将自动更改为全局对象,但该行为已在ES5规范中删除

In ES3 browsers you could pass null instead 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:

EventEmitter.prototype.emitArgs = function(event, args) {
    this.emit.apply(this, [event].concat(args));
}

此时您可以致电:

emitter.emitArgs('event', args);

编辑感谢@Esalija [ ] .concat

(EDIT thanks to @Esalija for [].concat)

这篇关于使用数组中的参数调用函数 - apply()而不使用上下文参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆