简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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