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

新手上路,请多包涵

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

     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
    }

原文由 Anderson Green 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 244
2 个回答

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

    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

原文由 KooiInc 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是一个将返回文档中定义的所有函数的函数,它所做的是遍历所有对象/元素/函数并仅显示类型为“函数”的那些。

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

这是一个 jsFiddle 工作演示

在最后添加函数,此代码段 getAllFunctions().slice(48, -4) 将仅返回 Vivaldi 中的用户定义函数。

原文由 Ashwin Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏