Return all functions defined in the Javascript file.

For the following script, how can I write a function that returns all script functions as an array? I would like to return an array of functions defined in the script so that I can print a summary of each 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 } 
+8
javascript reflection
Jul 01 2018-12-12T00:
source share
3 answers

Declare it in a pseudo-namespace, for example:

  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 
+9
Jul 01 2018-12-12T00:
source share

Here is a function that will return all the functions defined in the document, what it does is iterates through all objects / elements / functions and displays only those whose type is a "function".

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

Here is a working jsFiddle demo

+8
Jul 01 2018-12-12T00:
source share

 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>") } } 
+1
Jan 20 '16 at 22:47
source share



All Articles