19

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

    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
    }
4

4 回答 4

15

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

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

​这里是一个jsFiddle 工作演示 ​</p>

于 2012-07-01T04:40:33.103 回答
13

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

   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
于 2012-07-01T06:09:51.183 回答
2

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>")
	}
}

于 2016-01-20T22:47:11.800 回答
2

浪费了1个多小时。

这是.jsnode.js

1.安装节点模块:

npm i esprima

2.假设您在当前目录func1的文件中声明了如下所示的函数:a.js

var func1 = function (str1, str2) {
    //
};

3.你想得到它的名字,即func1代码如下:

const fs = require("fs");
const esprima = require("esprima");

let file = fs.readFileSync("./a.js", "utf8");

let tree = esprima.parseScript(file);
tree.body.forEach((el) => {
    if (el.type == "VariableDeclaration") {
        // console.log(el);
        console.log(el.declarations);
        console.log(el.declarations[0].id);
        console.log(el.declarations[0].id.name);
    }
});

4.您还可以获取其他详细信息,例如参数str1str2等,取消注释该console.log(el)行以查看其他详细信息。

5.您可以将以上两个代码部分放在一个文件中,以获取当前文件的详细信息(a.js)。

于 2020-08-29T22:59:21.477 回答