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

Return all of the functions that are defined in a Javascript file

本文关键字:函数 定义 Javascript 文件 返回      更新时间:2023-09-26

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

    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
    }

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

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 中的用户定义函数。

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

   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
浪费了

1 个多小时。

这是从node.js读取.js文件

1.安装节点模块:

npm i esprima

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

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)。

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