Home >Web Front-end >JS Tutorial >Does Crockford's Prototypal Inheritance Handle Nested Objects Correctly?
Crockford's Prototypal Inheritance: Issues with Nested Objects
In his book "Javascript: The Good Parts", Douglas Crockford presents a pattern for simplifying object inheritance. This pattern is based on the Object.create method, which allows the creation of a new object based on an existing prototype object.
While this pattern works well for flat objects, issues arise when dealing with nested objects. Overwriting a value of a nested object inherited using this pattern affects the nested element all the way up the prototype chain.
For example, in 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);
Changing the age property of person1 updates the age property of flatObj, but changing the age property of person2.info incorrectly updates the age property of nestObj.info.
This behaviour is not inherent to prototypal inheritance but rather to the way JavaScript handles nested objects. In JavaScript, a property of an object can either be an own property (defined on the object itself) or an inherited property (accessed through the prototype chain). When an object is created using Object.create, it inherits all own properties of its prototype object.
To avoid this issue, nested objects should be assigned explicitly to the new object. In the above example, the following code would create an independent info object for person2:
var person2 = Object.create(nestObj); person2.info = Object.create(nestObj.info);
This separation of nested objects ensures that changes made to the info object of person2 do not affect the info object of nestObj.
The above is the detailed content of Does Crockford's Prototypal Inheritance Handle Nested Objects Correctly?. For more information, please follow other related articles on the PHP Chinese website!