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

How Do You Retrieve Non-Enumerable Inherited Property Names in JavaScript?

Linda Hamilton
Release: 2024-11-09 04:23:02
Original
166 people have browsed it

How Do You Retrieve Non-Enumerable Inherited Property Names in JavaScript?

Retrieving Non-Enumerable Inherited Property Names in JavaScript

In JavaScript, accessing object properties is essential for object manipulation. While various methods exist for retrieving properties, they each focus on specific property types. This poses a challenge when attempting to access non-enumerable and non-own properties of an object.

Understanding Property Types

JavaScript properties can be categorized into three types:

  • Own Properties: Defined directly on the object itself.
  • Inherited Properties: Inherited from the object's prototype chain.
  • Enumerable Properties: Listed when using Object.keys() or a for...in loop.
  • Non-Enumerable Properties: Not included in the results of Object.keys() or a for...in loop.

The Challenge

The problem arises when attempting to retrieve non-enumerable, non-own properties of an object. Conventional methods like Object.keys() and for...in loops will not provide these properties.

The Solution: Traversing the Prototype Chain

To retrieve non-enumerable, non-own properties, a custom function can be created that traverses the object's prototype chain. The function utilizes Object.getOwnPropertyNames() to retrieve non-enumerable properties, including those inherited from the prototype chain.

Example Function

function getAllProperties(obj) {
  var allProps = [];
  var 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

Output:

[ "0", "1", "2", "length" ]
Copy after login

The above is the detailed content of How Do You 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template