返回所有的JavaScript文件中定义的函数返回所有的JavaScript文件中定义的函数(Ret

2019-06-14 11:28发布

对于下面的脚本,我怎么能写返回所有的脚本的功能,作为阵列的功能? 我想返回的脚本中定义的功能的阵列,这样我可以打印在脚本中定义的每个功能的摘要。

    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
    }

Answer 1:

声明它在一个伪命名空间,例如像这样:

   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


Answer 2:

这里是一个将返回文档中定义的所有功能的功能,它的作用是通过只有那些类型为“功能”的所有对象/元素/功能和显示迭代。

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

这里是一个的jsfiddle工作演示



Answer 3:

 function foo(){/*SAMPLE*/} function bar(){/*SAMPLE*/} function www_WHAK_com(){/*SAMPLE*/} for(var i in this) { if((typeof this[i]).toString()=="function"&&this[i].toString().indexOf("native")==-1){ document.write('<li>'+this[i].name+"</li>") } } 



文章来源: Return all of the functions that are defined in a Javascript file