javascript对象模型:奇怪的构造函数属性 [英] the javascript object model: strange constructor property

查看:71
本文介绍了javascript对象模型:奇怪的构造函数属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这段代码的行为令人费解,为什么 child 的构造函数不是 Child ?有人可以向我解释一下吗?

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


推荐答案

正如Pointy指出的那样,在他的回答中

As Pointy has pointed out, in his answer


constructor属性是对该对象的原型创建
的函数的
引用,而不是对象
本身。

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

我不能推荐Stoyan Stefanov的对象面向JavaScript的足够详细地介绍了原型和继承(如果可以的话,可以获得第二版,因为它可以解决第一版的一些批评)。

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

这篇关于javascript对象模型:奇怪的构造函数属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆