JavaScript继承:什么时候我的派生成员?

use*_*672 6 javascript inheritance prototypal-inheritance

看看下面的代码:

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

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

new Human();
Run Code Online (Sandbox Code Playgroud)

检查时new Human(),没有hairy会员.我希望有一个.还有另一种我想继承的方式Primate吗?涉及的东西Object.create()(ECMAScript5可以在我的场景中使用)?

Way*_*ett 4

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

一些东西:

  • 您通常想要修改打算用作构造函数(使用运算符)prototype函数new。换句话说,您想要设置prototypeon Human(而不是在的实例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(); 
Run Code Online (Sandbox Code Playgroud)

引用Human的 byh有一个属性叫hairy,其值为 true。

在前面的示例中,仅在调用hairy一次时才分配其值,这就是为什么必须分配 的实例。可以这样写,这样就不需要这样的初始化。PrimateHuman.prototypePrimate

例子:

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

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

var h = new Human();
Run Code Online (Sandbox Code Playgroud)