How can I have separate arrays in this general prototype?

Considering this:

var p = function(){}; p.prototype = { id : null, arr : []} var a = new p(); var b = new p(); a.id = 1; a.arr.push(5); alert(b.arr[0]); 

The warning reads 5 , which means that a.arr == b.arr, however a.id and b.id are separate (a.id! = B.id). How can I make a.arr! = B.arr?

Limitations:

p should be able to use new p() . Or, there must be a way to make unique p.

+4
source share
1 answer

If you want id and arr to be unique for each p instance, you need to instantiate them inside the p constructor. The prototype object should be used only for common constants and functions.

 var p = function(){ this.id = null; this.arr = []; }; var a = new p(); var b = new p(); a.id = 1; a.arr.push(5); alert(b.arr[0]); 
+3
source

Source: https://habr.com/ru/post/1413263/


All Articles