List of global user-defined functions in JavaScript?

Is it possible to get a list of custom functions in JavaScript?

I am currently using this, but it returns functions that are not user defined:

var functionNames = []; for (var f in window) { if (window.hasOwnProperty(f) && typeof window[f] === 'function') { functionNames.push(f); } } 
+27
javascript function
Jan 29 '09 at 22:49
source share
3 answers

I assume you want to filter your own functions. In Firefox, Function.toString() returns the body of a function, which for its own functions will look like:

 function addEventListener() { [native code] } 

You can map the pattern /\[native code\]/ in your loop and omit the functions that match.

+19
Jan 29 '09 at 23:07
source share

As Chetan Sastri suggested in his answer, you can check for the existence of [native code] inside the gated function:

 Object.keys(window).filter(function(x) { if (!(window[x] instanceof Function)) return false; return !/\[native code\]/.test(window[x].toString()) ? true : false; }); 

Or simply:

 Object.keys(window).filter(function(x) { return window[x] instanceof Function && !/\[native code\]/.test(window[x].toString()); }); 

in chrome you can get all non-local variables and functions:

 Object.keys(window); 
+8
Aug 09 '14 at 8:31
source share

Using Internet Explorer:

 var objs = []; var thing = { makeGreeting: function(text) { return 'Hello ' + text + '!'; } } for (var obj in window){window.hasOwnProperty(obj) && typeof window[obj] === 'function')objs.push(obj)}; 

Failed to report "item".

-3
Jan 08
source share



All Articles