简体   繁体   中英

javascript initializing object attributes?

I'm trying to write a wrapper on an array and I've come up with code below:

myList = function () { };
myList.prototype.innerArray = [];
myList.prototype.add = function(pt) { this.innerArray.push (pt); return this; };

For every object myList i create, I hope to get an empty attribute innerArray. But I'm afraid i haven't really understood the concept of prototypes yet, because:

m = new myList().add(4).add(5); 
m.innerArray.length;

returns 2, so far so good, but now I do:

j = new myList();
j.innerArray.length;

which returns also 2, and I would have expected 0 (a fresh new innerArray); I'm afraid i'm missing something fundamental.

You don't want to use prototype with innerArray. In your constructor simply do this.innerArray = [] and now you have an instance variable. By using prototype you are creating a class attribute (eg shared amongst class instances), not an instance variable (eg unique to an instance of the class).

You should do

myList = function () { this.innerArray = []; };

as this:

myList.prototype.innerArray = [];

creates innerArray variable common to all instances.

All instances of myList share the exact same prototype object. It is not copied or cloned to each instance. For functions this is fine because when you call foo.add() then this is the instance, allowing you to fetch per instance values. foo.add and bar.add are the same function object but this is different in each call. But with values directly on the prototype when you change them they change for all instances, since they all point to the same objects.

Instead you want to make a new array in the constructor:

myList = function () {
  this.innerArray = [];
};
myList.prototype.add = function(pt) {
  this.innerArray.push (pt);
  return this;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM