2

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,701
  • 3
  • 35
  • 50
hh54188
  • 14,887
  • 32
  • 113
  • 184
  • possible duplicate of [Confused about JavaScript prototypal inheritance](http://stackoverflow.com/questions/2182685/confused-about-javascript-prototypal-inheritance) –  Jul 08 '13 at 02:31
  • No, `Parent` is not created again. It is created once, when `new Parent()` is called, to set `Child.prototype`. –  Jul 08 '13 at 02:34

1 Answers1

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.

go-oleg
  • 19,272
  • 3
  • 43
  • 44