Home >Web Front-end >JS Tutorial >How Does Crockford's Prototypal Inheritance Handle Nested Objects and Their Inheritance?
Crockford's Prototypal Inheritance: Nested Objects and Inheritance
Douglas Crockford's "Javascript: The Good Parts" advocates for simplifying object inheritance by utilizing the Object.create() method to avoid the pitfalls of the new keyword. However, concerns have arisen regarding the behavior of nested objects when employing this pattern.
To illustrate the issue, consider the following example:
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);
In the above example, the person1 object inherits from the flatObj, and the person2 object inherits from the nestObj. When a property of a nested object is modified within an inherited object, it affects the nested object up the prototype chain.
person1.age = 69; // Overwrites `age` in `person1` person2.info.age = 96; // Overwrites `age` in `person2` and `nestObj`
As a result, the original nested object is altered, even though the change was intended solely for the inherited object.
This behavior is not consistent for flat objects. If flatObj.age is modified, it does not affect the age property of person1.
flatObj.age = 23; // Only affects `flatObj`
The inconsistency arises because nested objects are treated differently than flat objects in this inheritance pattern.
Addressing the Limitation
The limitation of the pattern with nested objects can be addressed by creating independent objects for nested properties before assigning them:
person3 = { sex: "male" } person3.info = Object.create(nestObj2.info);
By doing so, the info property of person3 becomes an independent object, unaffected by changes made to the nested object up the prototype chain.
However, it's important to note that this approach does not create completely independent objects. If a property of the nested object is deleted at the inherited object, it will also be deleted from the prototype object:
delete child.x; // (child).x.a == 0, because child inherits from parent
In summary, the Crockford's prototypal inheritance pattern with nested objects does have limitations. However, these limitations can be partially addressed by creating independent objects for nested properties before assigning them.
The above is the detailed content of How Does Crockford's Prototypal Inheritance Handle Nested Objects and Their Inheritance?. For more information, please follow other related articles on the PHP Chinese website!