How to Display All Methods of an Object
Problem:
Determine a method to list all available methods for a given object, similar to:
alert(show_all_methods(Math));
Expected output:
abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random,round, sin, sqrt, tan, …
Solution:
To enumerate all properties, including methods, belonging to an object, utilize the Object.getOwnPropertyNames() method. This method provides an array of property names:
console.log(Object.getOwnPropertyNames(Math)); //-> ["E", "LN10", "LN2", "LOG2E", "LOG10E", "PI", ...etc ]
Subsequently, employ the filter() method to isolate solely the methods:
console.log(Object.getOwnPropertyNames(Math).filter(function (p) { return typeof Math[p] === 'function'; })); //-> ["random", "abs", "acos", "asin", "atan", "ceil", "cos", "exp", ...etc ]
Note for ES3 Browsers:
In ES3 browsers, such as IE 8 and earlier, built-in object properties are not enumerable. However, this exclusion does not apply to objects like window and document, which are typically defined by the browser and likely enumerable.
The above is the detailed content of How Can I List All Methods of an Object?. For more information, please follow other related articles on the PHP Chinese website!