Home >Web Front-end >JS Tutorial >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.
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.
The above is the detailed content of Why do JavaScript Object Members Prototyped as Arrays Become Shared Across Class Instances?. For more information, please follow other related articles on the PHP Chinese website!