hooinator
hooinator

Reputation: 339

Inherited child objects share the same array property in JavaScript?

> function Parent() {this.arr = [];}
undefined
> function Child() {}
undefined
> Child.prototype = new Parent();
{ arr: [] }
> child1 = new Child();
{}
> child2 = new Child();
{}
> child1.arr.push('From child1');
1
> child2.arr
[ 'From child1' ]
>

Given the above, I would expect child2.arr to be empty as it is its own object. How can I have child1 and child2 contain their own arr? Thanks!

Upvotes: 0

Views: 38

Answers (3)

mamadum
mamadum

Reputation: 11

Look into inheritance in javascript

Basically if the property is not on the object you are looking into javascript looks into it's prototype and tries to find it there until it reaches the Object.

Your Child does not have property arr but it's prototype new Parent() does and that one is referred from Child1 and Child2.

Upvotes: 1

Pointy
Pointy

Reputation: 413720

You'll have to make the assignment in your constructor:

function Child() {
  this.arr = this.arr ? this.arr.slice(0) : [];
}

That gives each child a copy of the prototype's .arr array, if it exists. (It's just a shallow copy, and that's just a possible example.) Assignments to object properties always involve local ("own") properties of the target object, but references involve the prototype chain.

Also not that for fairly arcane reasons it's not a good idea to initialize a prototype like that. Better to use Object.create:

Child.prototype = Object.create(Parent.prototype);

That gives you a new object that uses the Parent prototype object as its prototype.

Here is a somewhat old but still interesting question on the topic.

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386560

function Parent() { this.arr = []; }
function Child() { this.parent = new Parent(); }
Child.prototype = new Parent();
var child1 = new Child();
var child2 = new Child();
child1.parent.arr.push('From child1');
alert(child2.parent.arr);

Upvotes: 0

Related Questions