gpt4 book ai didi

JavaScript 继承 : When where's my derived members?

转载 作者:数据小太阳 更新时间:2023-10-29 05:27:10 25 4
gpt4 key购买 nike

看看下面的代码:

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 必须被赋值的原因灵长类动物的实例。这可以改写为不需要这样的初始化。

例子:

function Primate() {}
Primate.prototype.hairy = true;

function Human() {}
Human.prototype = Primate.prototype;
Human.prototype.constructor = Human;

var h = new Human();

关于JavaScript 继承 : When where's my derived members?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9068835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com