JavaScript继承:When where'是我的派生成员

JavaScript inheritance: When where's my derived members?

本文关键字:我的 派生 成员 继承 When where JavaScript      更新时间:2023-09-26

查看以下代码:

function Primate() {
    this.prototype = Object;
    this.prototype.hairy = true;
}
function Human() {
    this.prototype = Primate;
}
new Human();

检查new Human()时,没有hairy成员。我希望会有一个。有没有其他方法可以让我继承Primate?涉及Object.create()的内容(ECMAScript5在我的场景中可以使用)?

编写代码时,使用new Human()创建的对象将具有一个名为prototype的属性,该属性的值是对Primate函数的引用。这显然不是你想要的(也不是特别的)。

几件事:

  • 您通常希望修改函数prototype,该函数将用作构造函数(使用new运算符)。换句话说,您希望在Human上设置prototype(而不是在Human实例上)。

  • 分配给prototype的值应该是所需类型的实例(或者,如果不需要初始化工作,则是所需的类型的prototype),而不是对其构造函数的引用。

  • 从来没有必要显式地将Object(或Object实例)分配给函数的prototype。这是隐含的。

你可能想要更像这样的东西:

function Primate() {
    this.hairy = true; 
}
function Human() {}
Human.prototype = new Primate();
Human.prototype.constructor = Human;
var h = new Human(); 

h引用的Human具有一个名为hairy的属性,其值为true。

在前面的示例中,hairy仅在调用Primate时被分配其值,这就是为什么必须为Human.prototype分配Primate的实例的原因。相反,可以将其编写为不需要这样的初始化。

示例:

function Primate() {}
Primate.prototype.hairy = true;
function Human() {}
Human.prototype = Primate.prototype;
Human.prototype.constructor = Human;
var h = new Human();