返回在 Javascript 文件中定义的所有函数
Return all of the functions that are defined in a Javascript file
对于下面的脚本,如何编写一个函数将脚本的所有函数作为数组返回?我想返回脚本中定义的函数数组,以便我可以打印脚本中定义的每个函数的摘要。
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.您还可以获取其他详细信息,例如参数str1
,str2
等,取消注释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>")
}
}
相关文章:
- 用嵌套函数和默认函数定义函数
- 使用Extjs进行函数定义
- JS中奇怪的函数定义语法
- 重写javascript函数定义
- 使用角度图时,我可以用函数定义数据点颜色吗
- modal.js中的匿名函数定义
- 为从AJAX调用中utlizes DATA参数的函数定义回调
- Emacs:在 etag 中查找函数定义
- Javascript:对象函数定义
- 为什么要在函数定义之外引用静态变量(函数属性)
- Ember 对象函数定义中的计算属性.js
- javascript/jQuery中函数定义的区别
- CoffeeScript 承诺与函数定义链接
- 如何在使用 eval() 评估 JavaScript 时将回调函数定义作为参数传递
- Javascript - 为什么下面的函数定义错误
- 使用函数声明时的自定义函数(也称为惰性函数定义)
- JavaScript 函数定义不正确
- jQuery off on 时是用匿名函数定义的
- 停止 IntelliJ 11 在启用 JSLint 时向每个嵌套函数定义添加“use strict”
- 为什么不是't我为这个函数定义的javascript函数