Passing function invocation as a parameter

2019-08-11 11:45发布

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条回答
走好不送
2楼-- · 2019-08-11 12:16

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", []);
查看更多
登录 后发表回答