31

Is it possible to get a list of the user defined functions in JavaScript?

I'm currently using this, but it returns functions which aren't user defined:

var functionNames = [];

for (var f in window) {
    if (window.hasOwnProperty(f) && typeof window[f] === 'function') {
        functionNames.push(f);
    }
}
AnnanFay
  • 9,573
  • 15
  • 63
  • 86
  • In Firefox this gave the expected results, namely all the functions on the global object, window. What false positives are you referring to? – Zach Jan 29 '09 at 23:29
  • I'm also wondering what false positives you are talking about? I also noticed that you haven't declared f, so it will end up in the global scope if it was part of an function. – some Jan 29 '09 at 23:46

3 Answers3

19

I'm assuming you want to filter out native functions. In Firefox, Function.toString() returns the function body, which for native functions, will be in the form:

function addEventListener() { 
    [native code] 
}

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

Chetan S
  • 23,637
  • 2
  • 63
  • 78
10

As Chetan Sastry suggested in his answer, you can check for the existance of [native code] inside the stringified 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-native variables and functions by:

Object.keys(window);
razz
  • 9,770
  • 7
  • 50
  • 68
-3

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

Fails to report 'thing'.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mozillanerd
  • 568
  • 4
  • 9
  • `thing` is a global object. `thing.makeGreeting` is a function but not global. Neither of these things should be caught. – AnnanFay Feb 03 '14 at 21:49