Prototyped Arrays in JavaScript: Shared Across Instances
In JavaScript, prototyping enables sharing behavior and data among instances of classes. However, when prototyping arrays, a unique behavior emerges: they become shared across all class instances rather than being private.
How Prototyping Works:
The prototype of an object serves as a blueprint for creating new objects. Properties and methods defined in the prototype are accessible by all objects that inherit from it. This concept differs from class-based languages where instances have separate copies of properties.
In the following example, the Sandwich class inherits from the Sandwich.prototype object:
function Sandwich() { // Uncomment to fix the problem //this.ingredients = []; } Sandwich.prototype = { "ingredients" : [], // ... };
Here, the ingredients property is defined on the prototype. This means all instances (e.g., cheeseburger, blt, etc.) will share this same array.
Shared Arrays:
The issue with prototyped arrays is that modifying one instance's array affects all others. This can lead to unexpected behavior, as observed in the example provided in the question. When either cheeseburger.ingredients or blt.ingredients is modified, it changes the same shared array inherited from Sandwich.prototype.
How to Avoid Sharing:
To create private arrays for each instance, define the property within the constructor, not the prototype:
function Sandwich() { this.ingredients = []; }
Here, the ingredients property is assigned to each newly created instance, making it distinct and isolated from other instances.
Shared vs. Instance-Specific Data:
The general rule is to assign instance-specific data within the constructor and shared data (e.g., methods) within the prototype. This allows for controlled access and flexibility in creating objects.
Additional Notes:
The above is the detailed content of Why Do Prototyped Arrays in JavaScript Become Shared Across Instances?. For more information, please follow other related articles on the PHP Chinese website!