4

Given 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 alert reads 5 meaning that a.arr == b.arr, however a.id and b.id are separate (a.id != b.id). How can I make it so that a.arr != b.arr?

Constraints:

p must be able to have new p() used. Or, there must be a way to make unique p's.

Travis J
  • 81,153
  • 41
  • 202
  • 273
  • What might be helpful is to add the array as a prototype after you create it. So then the id isn't persistent across object creation, but the array contents are, if I am understanding what you are trying to do. – Andy May 19 '12 at 01:19

1 Answers1

3

If you want id and arr to be unique to each instance of p you need to instantiate them inside the p constructor. The prototype object should only be used for shared 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]);
Brian Zengel
  • 546
  • 1
  • 3
  • 11