Question

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?

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top