简体   繁体   English

将函数调用作为参数传递

[英]Passing function invocation as a parameter

I have an object with functions as properties: 我有一个具有函数作为属性的对象:

var o = {
   "f1":function(){alert('invoke one');},
   "f2":function(){alert('invoke two');},
   "f3":function(){alert('invoke three');}
};

I am planning to use _.each of http://underscorejs.org/ to invoke them. 我打算使用http://underscorejs.org/的 _.each来调用它们。 So, my invocation will look like 因此,我的调用看起来像

_.each(o, function(f){f();});

what irritates is the second parameter for _.each. 令人讨厌的是_.each的第二个参数。 If there is a such function "invoke", I could just call _.each(o,invoke); 如果有这样的函数“调用”,我可以只调用_.each(o,invoke);

I know that defining invoke is fairly easy: 我知道定义调用非常容易:

function invoke (f){f();}

but I just want to know if there is anything built-in that I am not aware of. 但是我只想知道是否有我不知道的内置功能。

There is no native function that does this. 没有本机函数可以执行此操作。 You could have a bit fun with .call 您可以对.call感到开心

var invoke = Function.prototype.call.bind(Function.prototype.call)

but declaring invoke like you did is much simpler. 但是像您一样声明invoke很简单。

With Underscore.js, you can however use the invoke method : 通过Underscore.js,您可以使用invoke方法

_.invoke(o, Function.prototype.call);
_.invoke(o, "call");
_.invoke(o, Function.prototype.apply, []);
_.invoke(o, "apply", []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM