返回Javascript文件中定义的所有函数

And*_*een 12 javascript reflection

对于以下脚本,如何编写一个将所有脚本函数作为数组返回的函数?我想返回脚本中定义的函数数组,以便我可以打印脚本中定义的每个函数的摘要.

    function getAllFunctions(){ //this is the function I'm trying to write
        //return all the functions that are defined in the script where this
        //function is defined.
        //In this case, it would return this array of functions [foo, bar, baz,
        //getAllFunctions], since these are the functions that are defined in this
        //script.
    }

    function foo(){
        //method body goes here
    }

    function bar(){
        //method body goes here
    }

    function baz(){
        //method body goes here
    }
Run Code Online (Sandbox Code Playgroud)

Ash*_*ngh 12

这是一个函数,它将返回文档中定义的所有函数,它的作用是遍历所有对象/元素/函数,并仅显示其类型为"function"的函数.

function getAllFunctions(){ 
        var allfunctions=[];
          for ( var i in window) {
        if((typeof window[i]).toString()=="function"){
            allfunctions.push(window[i].name);
          }
       }
    }
Run Code Online (Sandbox Code Playgroud)

这里是一个的jsfiddle工作演示

  • 将`&& window [i] .toString().indexOf("native")== - 1`添加到if修复中. (4认同)
  • 这样做的问题是它将捕获在附加到window的先前脚本中定义的所有功能。首先将东西扔到窗户上是一个非常糟糕的主意。 (2认同)

Koo*_*Inc 12

在伪名称空间中声明它,例如:

   var MyNamespace = function(){
    function getAllFunctions(){ 
      var myfunctions = [];
      for (var l in this){
        if (this.hasOwnProperty(l) && 
            this[l] instanceof Function &&
            !/myfunctions/i.test(l)){
          myfunctions.push(this[l]);
        }
      }
      return myfunctions;
     }

     function foo(){
        //method body goes here
     }

     function bar(){
         //method body goes here
     }

     function baz(){
         //method body goes here
     }
     return { getAllFunctions: getAllFunctions
             ,foo: foo
             ,bar: bar
             ,baz: baz }; 
    }();
    //usage
    var allfns = MyNamespace.getAllFunctions();
    //=> allfns is now an array of functions. 
    //   You can run allfns[0]() for example
Run Code Online (Sandbox Code Playgroud)

  • 它有效,但这看起来有点多余:return {getAllFunctions:getAllFunctions,foo:foo,bar:bar,baz:baz}; 是否可以在不对每个函数的名称进行硬编码的情况下执行此操作? (3认同)