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

How to List All Methods of an Object in JavaScript?

Patricia Arquette
Release: 2024-10-19 16:17:02
Original
629 people have browsed it

How to List All Methods of an Object in JavaScript?

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!