0
> 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!

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Adding the assignment in the child constructor works great! Thanks!
1

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.

Comments

0
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.