Home >Web Front-end >JS Tutorial >How Does Crockford's Prototypal Inheritance Handle Nested Objects and Property Modification?
Crockford's Prototypal Inheritance: Issues with Nested Objects
Douglas Crockford's prototypal inheritance pattern, outlined in his book "Javascript: The Good Parts," simplifies object inheritance and avoids the confusion associated with the "new" keyword. However, when attempting to inherit from nested objects using this pattern, an issue arises: overwriting a nested object property affects the entire prototype chain.
Consider the following code:
var flatObj = { firstname: "John", lastname: "Doe", age: 23 } var person1 = Object.create(flatObj); var nestObj = { sex: "female", info: { firstname: "Jane", lastname: "Dough", age: 32 } } var person2 = Object.create(nestObj); var nestObj2 = { sex: "male", info: { firstname: "Arnold", lastname: "Schwarzenneger", age: 61 } } var person3 = { sex: "male" } person3.info = Object.create(nestObj2.info); // now change the objects: person1.age = 69; person2.info.age = 96; person3.info.age = 0; // prototypes should not have changed: flatObj.age // 23 nestObj.info.age // 96 ??? nestObj2.info.age // 61 // now delete properties: delete person1.age; delete person2.info.age; delete person3.info.age; // prototypes should not have changed: flatObj.age // 23 nestObj.info.age // undefined ??? nestObj2.info.age // 61
In this example, after inheriting from the nested object nestObj, changing a property of the nested object in person2 affects the prototype nestObj, and similarly for person3's nested object. This is unexpected behavior and undermines the pattern's intended purpose of isolating changes to individual objects.
The reason for this inconsistency lies in the fundamental nature of inheritance in JavaScript objects. When an object inherits from another, it creates a reference to that object's properties rather than creating independent copies. This means that any changes made to the inherited properties will reflect in both the child object and the prototype.
To avoid this issue, one must explicitly create a new object for nested properties before inheriting them. This ensures that changes to the nested properties are isolated to the child object. Therefore, the correct code should be:
person3.info = Object.create(nestObj2.info); // Create a new object for the nested property person3.info.age = 0; // Change the age property without affecting the prototype
The above is the detailed content of How Does Crockford's Prototypal Inheritance Handle Nested Objects and Property Modification?. For more information, please follow other related articles on the PHP Chinese website!