1

Suppose I have a child function:

function Child() {}

and have a parent function:

function Parent() {}

then I set the Child's prototype to a new instance of Parent:

Child.prototype = new Parent()

the confusion is each time when I create new an instance of Child

var c = new Child()

Would the Parent be created again?

icedwater
4,8943 gold badges40 silver badges54 bronze badges
asked Jul 8, 2013 at 2:25
2
  • possible duplicate of Confused about JavaScript prototypal inheritance Commented Jul 8, 2013 at 2:31
  • No, Parent is not created again. It is created once, when new Parent() is called, to set Child.prototype. Commented Jul 8, 2013 at 2:34

1 Answer 1

1

It is created only once. Every time you call new Child() a new Child object is created and the same Parent object is set to be its prototype. You can confirm this by doing the following (jsfiddle):

function Child() {}
function Parent() {
 this.aParentProp = { name : "Parent" };
}
Child.prototype = new Parent();
var c1 = new Child();
var c2 = new Child();
if(Object.getPrototypeOf(c1) === Object.getPrototypeOf(c2)) {
 alert("same prototype!");
}
if(c1.aParentProp === c2.aParentProp) {
 alert("same property!");
}

Both c1 and c2 have the same prototype using Object.getPrototypeOf. Also, both c1's and c2's aParentProp points to the same object instance showing that both c1 and c2 share the same Parent object for their prototype.

answered Jul 8, 2013 at 2:34
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.