javascript运行一堆函数

Har*_*rry 1 javascript

如何在不知道名字的情况下执行一系列功能?

var theseFn = function () {
  func1 : function () {},
  func2 : function () {}
}
Run Code Online (Sandbox Code Playgroud)

我想在这些中运行所有内容.我该怎么做呢?谢谢.

Sto*_*ive 6

这将执行对象上的所有函数,假设没有参数:

for (var i in theseFn) if (typeof(theseFn[i]) === "function") theseFn[i]();
Run Code Online (Sandbox Code Playgroud)


ick*_*fay 5

您可以使用hasOwnProperty带括号表示法的for-in循环(当然带有检查)来进行对象属性访问:

for(var functionName in theseFn) {
    if(theseFn.hasOwnProperty(functionName)&&typeof theseFn[functionName]=="function") {
        theseFn[functionName]();
    }
}
Run Code Online (Sandbox Code Playgroud)