我有一个以函数作为属性的对象:
var o = {
"f1":function(){alert('invoke one');},
"f2":function(){alert('invoke two');},
"f3":function(){alert('invoke three');}
};
我打算使用 _.each of http://underscorejs.org/调用它们。 所以,我的调用看起来像
_.each(o, function(f){f();});
令人恼火的是_.each 的第二个参数。如果有这样的函数“调用”,我可以调用 _.each(o,invoke);
我知道定义 invoke 相当简单:
function invoke (f){f();}
但我只想知道是否有任何我不知道的内置内容。
最佳答案
没有执行此操作的 native 函数。你可以玩得开心 .call
var invoke = Function.prototype.call.bind(Function.prototype.call)
但是像您那样声明invoke
要简单得多。
使用 Underscore.js,您可以使用 invoke
method :
_.invoke(o, Function.prototype.call);
_.invoke(o, "call");
_.invoke(o, Function.prototype.apply, []);
_.invoke(o, "apply", []);
关于javascript - 将函数调用作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26979538/