![]() |
VOOZH | about |
Inherited properties are those that an object acquires from its prototype chain rather than defining them directly. To prevent overwriting these inherited properties, it's important to ensure that any modifications or additions to the object do not accidentally affect properties inherited from its prototypes.
Here are several methods to achieve this
Before assigning a value to a property, verify that the property is an owned property of the object using the hasOwnProperty() method.
Cannot overwrite an inherited property.
In this example, childObj inherits inheritedProp from parentObj. The hasOwnProperty() check ensures that inheritedProp is not overwritten in childObj.
Define properties with specific attributes to control their writability and configurability, preventing unintended modifications.
protected value
By setting writable and configurable to false, inheritedProp cannot be modified or deleted in parObj or any of its descendants.
When adding new properties to an object, choose property names that do not conflict with inherited properties to prevent accidental overwriting.
original value own value
By using unique property names, you ensure that inherited properties remain unaffected.
If you need an object without any inherited properties, create it with Object.create(null). This approach provides an object with no prototype, eliminating inherited properties.
value undefined
Since obj has no prototype, it doesn't inherit any properties, including hasOwnProperty.
When iterating over an object's properties, ensure that only its own properties are considered, excluding inherited ones.
ownProp: own value
The for...in loop iterates over all enumerable properties, including inherited ones. The hasOwnProperty() check filters out inherited properties, ensuring only own properties are processed.