Home > Article > Web Front-end > Why Do Prototype Arrays in JavaScript Get Shared Across Class Instances?
Understanding Prototype Sharing in JavaScript: Objects Inherited from Prototypes
In JavaScript, objects inherit properties from their prototypes. One aspect to consider is how arrays defined as prototype properties behave within class instances.
As observed, prototyped arrays are not private to individual class instances but are instead shared among all instances. This behavior arises because the prototype of an object acts as an object itself. Prototype properties are shared by all objects derived from that specific prototype.
Consider the following example:
function Sandwich() { // Uncomment this to fix the problem //this.ingredients = []; } Sandwich.prototype = { "ingredients" : [], "addIngredients" : function( ingArray ) { for( var key in ingArray ) { this.addIngredient( ingArray[ key ] ); } }, "addIngredient" : function( thing ) { this.ingredients.push( thing ); } }
In this example, an array named "ingredients" is defined as a prototype property of the "Sandwich" function. If "this.ingredients = [];" is commented out within the constructor, the following behavior occurs:
When a new instance of "Sandwich" is created (such as "cheeseburger" or "blt"), these instances initially inherit the "ingredients" array from the prototype. Modifications made to this array, such as adding ingredients to "cheeseburger," also affect the "ingredients" arrays of all other "Sandwich" instances. This shared behavior arises from the fact that all instances reference the same array, not individual copies.
To resolve this issue and create a separate array for each instance, the "ingredients" array must be defined within the constructor:
function Sandwich() { this.ingredients = []; }
This modification assigns a new array to each instance of "Sandwich" during construction, ensuring that any changes made to the "ingredients" array are instance-specific.
In summary, arrays defined as prototype properties are shared among all objects that inherit from that prototype. To create instance-specific data, such as arrays, they must be defined within the constructor. This understanding is crucial for effective use of inheritance and object-oriented programming in JavaScript.
The above is the detailed content of Why Do Prototype Arrays in JavaScript Get Shared Across Class Instances?. For more information, please follow other related articles on the PHP Chinese website!