"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve Inherited Non-Enumerable Properties in JavaScript?

How to Retrieve Inherited Non-Enumerable Properties in JavaScript?

Published on 2024-11-13
Browse:739

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3