Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the javascript object model: strange constructor property

Tags:

javascript

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
like image 294
einarmagnus Avatar asked Jan 22 '23 07:01

einarmagnus


2 Answers

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).

like image 143
Russ Cam Avatar answered Jan 31 '23 11:01

Russ Cam


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

like image 42
Pointy Avatar answered Jan 31 '23 11:01

Pointy