Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of global user defined functions in JavaScript?

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);
    }
}
like image 496
AnnanFay Avatar asked Jan 29 '09 22:01

AnnanFay


People also ask

What are the user-defined functions in JavaScript?

A user-defined function (UDF) is a function that you can create yourself and then add to the list of available functions in Excel when Excel doesn't provide the type of function that you want right out of the box.

What are all types of user-defined functions?

There are two main types of user-defined functions in SQL based on the data they return: Scalar functions: These types of functions return a single value, i.e float, int, varchar, datetime, etc. Table-Valued functions: These functions return tables.

How many user-defined functions are there?

There can be 4 different types of user-defined functions, they are: Function with no arguments and no return value. Function with no arguments and a return value. Function with arguments and no return value.


2 Answers

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.

like image 177
Chetan S Avatar answered Oct 10 '22 08:10

Chetan S


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); 
like image 26
razz Avatar answered Oct 10 '22 09:10

razz