Home > Web Front-end > JS Tutorial > Why Does Overwriting Nested Objects in Crockford's Prototypal Inheritance Pattern Affect the Prototype?

Why Does Overwriting Nested Objects in Crockford's Prototypal Inheritance Pattern Affect the Prototype?

DDD
Release: 2024-12-09 15:46:11
Original
202 people have browsed it

Why Does Overwriting Nested Objects in Crockford's Prototypal Inheritance Pattern Affect the Prototype?

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);
Copy after login

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,
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template