Home >Web Front-end >JS Tutorial >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><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
}
Example Usage
To demonstrate the functionality of the getAllProperties() function, consider the following array object:
console.log(getAllProperties([1,2,3]));
Output:
[ 'length' ]
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!