将函数调用作为参数传递 [英] Passing function invocation as a parameter

查看:40
本文介绍了将函数调用作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以函数为属性的对象:

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

我打算使用 http://underscorejs.org/ 的 _.each 来调用它们.所以,我的调用看起来像

I am planning to use _.each of http://underscorejs.org/ to invoke them. So, my invocation will look like

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

让人恼火的是_.each的第二个参数.如果有这样的函数调用",我可以调用 _.each(o,invoke);

what irritates is the second parameter for _.each. If there is a such function "invoke", I could just call _.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

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

但是像您一样声明 invoke 就简单多了.

but declaring invoke like you did is much simpler.

使用 Underscore.js,您可以使用 invoke 方法:

With Underscore.js, you can however use the invoke method:

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

这篇关于将函数调用作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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