In JavaScript, object properties can be defined in two ways: directly on the object or as properties of the object's prototype. This behavior has significant implications when dealing with arrays.
By default, prototyped arrays are shared among all instances of a class, leading to unexpected behavior. For instance, if the prototype of a class contains an empty array, all instances will reference the same array. This can be observed in the following example:
function Sandwich() { // Uncomment 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); } }; var cheeseburger = new Sandwich(); cheeseburger.addIngredients(["burger", "cheese"]); var blt = new Sandwich(); blt.addIngredients(["bacon", "lettuce", "tomato"]); print_r("Cheeseburger contains:", cheeseburger.ingredients);
In this example, both cheeseburger and blt share the same ingredients array, even though they are different instances. Adding an ingredient to cheeseburger also affects blt, highlighting the shared nature of the array.
To rectify this behavior, it is recommended to define arrays directly on the object itself, rather than as prototype properties. This ensures that each instance has its own private array. The following modification to the code fixes the problem:
function Sandwich() { this.ingredients = []; }
By defining the array in the constructor, each instance of Sandwich will have its own private copy of the array, eliminating the sharing behavior.
In summary, prototyped arrays are shared among all instances of a class in JavaScript. To create private arrays for each instance, it is necessary to define the array directly on the object itself in the constructor. This distinction is crucial for understanding and managing object behavior in JavaScript.
以上がJavaScript オブジェクトのメンバーは配列としてプロトタイプ化され、共有またはプライベートですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。