"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why do JavaScript Object Members Prototyped as Arrays Become Shared Across Class Instances?

Why do JavaScript Object Members Prototyped as Arrays Become Shared Across Class Instances?

Published on 2024-12-22
Browse:902

Why do JavaScript Object Members Prototyped as Arrays Become Shared Across Class Instances?

JavaScript Object Members Prototyped as Arrays: Shared Across Class Instances

When prototyping arrays in JavaScript, it's crucial to understand that these members become shared among all class instances. This behavior may seem counterintuitive if you're accustomed to private object members.

Behavior Explanation

JavaScript's prototype mechanism allows objects to inherit properties and methods from a parent object, known as the prototype. When you define an array as a property in the prototype, it becomes accessible to all objects that inherit from that prototype.

The example script demonstrates this behavior:

function Sandwich() {
    // Uncomment this to fix the problem
    //this.ingredients = [];
}

With the commented line uncommented, each Sandwich instance would have its own private ingredients array. However, with the line commented out, all instances share the same prototype array.

This means that adding an ingredient to cheeseburger also updates the ingredients of blt and spicy_chicken_sandwich. To prevent this, you must define the ingredients array within the constructor, as shown in the updated example below:

function Sandwich() {
    this.ingredients = [];
}

Prototype vs. Instance

It's essential to distinguish between prototype properties and instance properties. Prototype properties are shared by all objects that inherit from that prototype, while instance properties are unique to each object.

  • Assign properties to the prototype to define shared data or methods.
  • Assign properties to the instance inside the constructor to define instance-specific data.

Code Modifications to Fix the Behavior

In the example script, uncommenting the line this.ingredients = []; within the Sandwich constructor ensures that each instance has its own ingredient array, as intended.

Conclusion

Understanding the behavior of prototyped arrays in JavaScript is crucial to avoid unexpected sharing among class instances. Always remember that data that should be instance-specific should be defined within the constructor, while shared data can be assigned to the prototype via inheritance.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3