Issues with Nested Objects in Crockford's Prototypal Inheritance Pattern
Douglas Crockford's prototypal inheritance pattern is a simplified alternative to the built-in "new" keyword in JavaScript. However, users may encounter issues when attempting to inherit from nested objects using this pattern.
In this inheritance pattern, a target object's prototype is set to another object, inheriting its properties. If a nested property is overwritten in the target object, the change propagates all the way up the prototype chain. This behavior is inconsistent with the expected notion of nested objects.
Consider the example provided:
var nestObj = { sex: "female", info: { firstname: "Jane", lastname: "Dough", age: 32, }, }; var person2 = Object.create(nestObj);
When the property person2.info.age is overwritten, it also changes the age of the nested object in the prototype (nestObj.info.age). This may be unexpected.
According to the answer, this behavior is not an inconsistency. Nested objects are not considered distinct entities. Instead, they are either own properties of the object or inherited from the prototype. Overwriting a property value on a nested object affects both the own property and the inherited property.
To change a nested property independently, it must be assigned a new object reference.
person2.info = { firstname: "Jane", lastname: "Dough", age: 32, };
This creates a new nested object that is independent from the prototype. Overwriting properties on this new object will not affect the prototype.
The above is the detailed content of Why Does Overwriting Nested Objects in Crockford's Prototypal Inheritance Pattern Affect the Prototype?. For more information, please follow other related articles on the PHP Chinese website!