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

How to Retrieve Non-Enumerable Inherited Property Names in JavaScript?

Susan Sarandon
Release: 2024-11-09 07:57:02
Original
842 people have browsed it

How to Retrieve Non-Enumerable Inherited Property Names in JavaScript?

Obtaining Non-Enumerable Inherited Property Names of an Object in JavaScript

JavaScript provides various methods for accessing object properties based on specific requirements. However, none of these methods allow for the retrieval of non-enumerable, non-own properties. This article explores alternative approaches to extracting such properties.

Solution: Leveraging getOwnPropertyNames and Prototype Chaining

Since Object.getOwnPropertyNames() can retrieve non-enumerable properties, it can be combined with prototype chain traversal. The following JavaScript function, getAllProperties(), iterates through the prototype chain of an object and compiles a list of all its non-enumerable, non-own properties:

function getAllProperties(obj){</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">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
Copy after login

}

Example Usage

To demonstrate the functionality of the getAllProperties() function, consider the following array object:

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

Output:

[ 'length' ]
Copy after login

The output lists the non-enumerable property 'length', which belongs to the Array.prototype chain.

The above is the detailed content of How to Retrieve Non-Enumerable Inherited Property Names 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template