Home > Web Front-end > JS Tutorial > How to Retrieve Non-Enumerable Inherited Properties in JavaScript?

How to Retrieve Non-Enumerable Inherited Properties in JavaScript?

Barbara Streisand
Release: 2024-11-10 20:20:03
Original
779 people have browsed it

How to Retrieve Non-Enumerable Inherited Properties in JavaScript?

Retrieving Non-Enumerable Inherited Properties

Determining the existence of non-enumerable inherited properties is crucial in JavaScript. Although methods like Object.keys() and Object.getOwnPropertyNames() provide access to object properties, they exclude inherited non-enumerable attributes.

To bridge this gap, we can leverage the Object.getOwnPropertyNames() method in conjunction with prototype chain traversal. This approach allows us to identify non-enumerable properties at any level of the inheritance hierarchy.

Here's a function that demonstrates this technique:

function getAllProperties(obj) {
    var allProps = []
      , curr = obj;
    do {
        var props = Object.getOwnPropertyNames(curr);
        props.forEach(function(prop) {
            if (allProps.indexOf(prop) === -1)
                allProps.push(prop);
        });
    } while (curr = Object.getPrototypeOf(curr));
    return allProps;
}

console.log(getAllProperties([1,2,3]));
Copy after login

By combining Object.getOwnPropertyNames() with prototype chain traversal, we can now retrieve a complete list of both enumerable and non-enumerable properties of an object, including those inherited from its parent prototypes. This approach provides a comprehensive view of all properties, regardless of their visibility or ownership status.

The above is the detailed content of How to Retrieve Non-Enumerable Inherited Properties in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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