Listing All Methods of an Object
In JavaScript, you can enumerate the methods of an object using the Object.getOwnPropertyNames() method. However, you may also want to filter out the non-method properties, ensuring you only get the desired functionality.
Object.getOwnPropertyNames()
Object.getOwnPropertyNames() returns an array of all the properties (both enumerable and non-enumerable) that belong to a given object. For instance:
console.log(Object.getOwnPropertyNames(Math)); //-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]
Filtering Methods
To obtain only the methods, you can combine Object.getOwnPropertyNames() with the filter() method:
console.log(Object.getOwnPropertyNames(Math).filter(function (p) { return typeof Math[p] === 'function'; })); //-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]
ES3 Browser Compatibility
In ES3 browsers (such as IE 8 or below), built-in object properties are not enumerable, except for those defined by the browser itself (e.g., window, document). Consequently, using the above approach will not capture all methods in these environments.
IE Bug with { DontEnum }
In Internet Explorer, there is a bug that causes it to skip over properties with the { DontEnum } attribute in an object if there is a property with the same name in the prototype chain that also has { DontEnum }. This means that naming object properties carefully is essential when working with IE to avoid potential issues.
The above is the detailed content of How to List All Methods of an Object in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!