Return all of the functions that are defined in a Javascript file
For the following script, how can I write a function that returns all of the script's functions as an array? I'd like to return an array of the functions defined in the script so that I can print a summary of every function that is defined in the script.
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
}
Solution 1:
Here is a function that will return all functions defined in the document, what it does is it iterates through all objects/elements/functions and displays only those whose type is "function".
function getAllFunctions(){
var allfunctions=[];
for ( var i in window) {
if((typeof window[i]).toString()=="function"){
allfunctions.push(window[i].name);
}
}
}
Here is a jsFiddle working demo
Solution 2:
Declare it in a pseudo namespace, for example like this:
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
Solution 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>")
}
}
Solution 4:
More than 1 hour wasted on this.
This is read .js
file from node.js
1.Install a node module:
npm i esprima
2.Assume you have a function func1
declared like below, in a file a.js
in current directory:
var func1 = function (str1, str2) {
//
};
3.And you would like to get name of it, that is func1
, the code is below:
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.You can also get other details like parameters str1
, str2
, etc, uncomment the console.log(el)
line to see other details.
5.You can put both above code parts in one file, to get the details of current file (a.js
).