Passing function invocation as a parameter

ⅰ亾dé卋堺 提交于 2019-12-13 00:01:16

问题


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. So, my invocation will look like

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

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.


回答1:


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)

but declaring invoke like you did is much simpler.

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", []);


来源:https://stackoverflow.com/questions/26979538/passing-function-invocation-as-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!