gpt4 book ai didi

javascript - 将函数调用作为参数传递

转载 作者:行者123 更新时间:2023-11-30 17:11:10 25 4
gpt4 key购买 nike

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

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/

25 4 0
文章推荐: javascript - AWS S3 ajax PUT 返回 'The request signature we calculated does not match the signature you provided' ?
文章推荐: javascript - 从 grunt-contrib-connect 请求对象获取数据
文章推荐: javascript - 如何将加载到 中的元素样式设置为数据