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 exp开发者_运维百科lain 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
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).
The "constructor" property is a reference to the function that created the object's prototype, not the object itself.
精彩评论