List of global user defined functions in JavaScrip

2019-01-07 16:43发布

问题:

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

回答1:

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.



回答2:

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


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