Home > Web Front-end > JS Tutorial > body text

How Can I List All Methods of an Object?

Patricia Arquette
Release: 2024-10-19 16:22:02
Original
932 people have browsed it

How Can I List All Methods of an Object?

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));
Copy after login

Expected output:

abs, acos, asin, atan, atan2, ceil, cos, exp, floor, log, max, min, pow, random,round, sin, sqrt, tan, …
Copy after login

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 ]
Copy after login

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 ]
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template