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);
    }
}
2
  • In Firefox this gave the expected results, namely all the functions on the global object, window. What false positives are you referring to? Commented Jan 29, 2009 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. Commented Jan 29, 2009 at 23:46

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-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'.

1 Comment

thing is a global object. thing.makeGreeting is a function but not global. Neither of these things should be caught.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.