einarmagnus
einarmagnus

Reputation: 3590

the javascript object model: strange constructor property

I find the behaviour of this piece of code puzzling, why is the constructor of child not Child? Can someone please explain this to me?

function Parent() {
    this.prop1 = "value1";
    this.prop2 = "value2";
}

function Child() {
    this.prop1 = "value1b";
    this.prop3 = "value3";
}
Child.prototype = new Parent();

var child = new Child();

// this is expected
console.log(child instanceof Child); //true
console.log(child instanceof Parent); //true

// what??
console.log(child.constructor == Child); //false
console.log(child.constructor == Parent); //true

Upvotes: 4

Views: 702

Answers (2)

Russ Cam
Russ Cam

Reputation: 125538

As Pointy has pointed out, in his answer

The "constructor" property is a reference to the function that created the object's prototype, not the object itself.

The usual way to deal with this is to augment the object's prototype constructor property after assigning to the prototype

function Parent() {
    this.prop1 = "value1";
    this.prop2 = "value2";
}

function Child() {
    this.prop1 = "value1b";
    this.prop3 = "value3";
}
Child.prototype = new Parent();

// set the constructor to point to Child function
Child.prototype.constructor = Child;

var child = new Child();

// this is expected
console.log(child instanceof Child); //true
console.log(child instanceof Parent); //true

// corrected
console.log(child.constructor == Child); // now true
console.log(child.constructor == Parent); // now false

console.log(Child.prototype.constructor); // Child
console.log(Parent.prototype.constructor); // Parent

I can't recommend Stoyan Stefanov's Object Oriented JavaScript enough which covers Prototype and Inheritance in some detail (get the second edition if you can as it addresses some critiques of the first edition).

Upvotes: 5

Pointy
Pointy

Reputation: 414086

The "constructor" property is a reference to the function that created the object's prototype, not the object itself.

Upvotes: 4

Related Questions