Home > Article > Web Front-end > 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]));
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!