List of global user defined functions in JavaScript?
Asked Answered
N

3

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);
    }
}
Noneffective answered 29/1, 2009 at 22:49 Comment(2)
In Firefox this gave the expected results, namely all the functions on the global object, window. What false positives are you referring to?Blinders
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.Haplo
C
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.

Cholera answered 29/1, 2009 at 23:7 Comment(0)
D
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);
Digestive answered 9/8, 2014 at 8:31 Comment(0)
P
-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'.

Paeon answered 8/1, 2010 at 3:4 Comment(1)
thing is a global object. thing.makeGreeting is a function but not global. Neither of these things should be caught.Noneffective

© 2022 - 2024 — McMap. All rights reserved.