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

How to Retrieve Inherited Non-Enumerable Properties in JavaScript?

DDD
DDDOriginal
2024-11-08 22:36:02525browse

How to Retrieve Inherited Non-Enumerable Properties in JavaScript?

Retrieving Inherited Non-Enumerable Properties

In JavaScript, accessing object properties relies on various methods tailored to specific requirements. However, when it comes to obtaining non-enumerable, non-own properties, there's no straightforward mechanism.

To address this, a custom function can be utilized that combines Object.getOwnPropertyNames() to obtain non-enumerable properties and walks up the prototype chain to retrieve inherited ones.

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]));

In this example, [1, 2, 3] is an inherited property, and the function successfully retrieves it without inheriting its enumeration status. This approach empowers developers with the ability to access non-enumerable inherited properties, which is crucial for certain scenarios involving prototypes and object inheritance.

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

Statement:
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