通过伪经典实例化掌握原型继承 (JavaScript)

Grasping prototypical Inheritance through pseudoclassical instantiation (JavaScript)

我正在尝试通过 JavaScript 利用继承的测试套件。下面是我到目前为止的代码片段:

var Infant = function() {
    this.age  = 0;
    this.color = 'pink';
    this.food = 'milk';

};
Infant.prototype.eat = function(){
    return this.eat;
}


var Adolescent = function() {

    this.age = 5;
    this.height = 'short';
    this.job = 'keep on growing';

};

我想继承 Infant class 的食物 属性 和 eat 方法,但我的尝试没有成功。我最初的想法是分配 this.Adolescent = Infant.food;但这没有用。我知道我需要将 Infant 设置为 Superclass 但我正在旋转我的轮子

在 JavaScript 中使用构造函数进行继承时,您:

  1. 使“派生”构造函数的prototype属性成为原型为“基”构造函数的prototype属性的对象.

  2. 将“派生”构造函数的 prototype 属性 上的 constructor 属性 设置为指向“派生”构造函数。

  3. 使用正确的 this.

    从“派生”构造函数调用“基础”构造函数

像这样:

var Infant = function() {
    this.age  = 0;
    this.color = 'pink';
    this.food = 'milk';
};
Infant.prototype.eat = function(){
    return /*...something...*/; // Returning `this.eat` doesn't make any sense, that's the function we're in
};

var Adolescent = function() {

    // #3 Give super a chance to initialize the instance, you can pass args if appropriate
    Infant.call(this);

    this.age = 5;
    this.height = 'short';
    this.job = 'keep on growing';
};

// Set up Adolescent's prototype, which uses Infant's prototype property as its prototype
Adolescent.prototype = Object.create(Infant.prototype);     // #1
Object.defineProperty(Adolescent.prototype, "constructor",  // #2
    value: Adolescent,
    writable: true,
    configurable: true
});
// (In pre-ES5 environments that don't event have `Object.defineProperty`, you'd use
// an assignment instead: `Adolescent.prototype.constructor = Adolescent;`

Object.create 是在 ES5 中添加的,因此它不会像 IE8 中那样出现在过时的 JavaScript 引擎上。不过,上面使用的 single-argument 版本可以是 easily shimmed

在 ES2015 中,我们可以选择使用新的 class 语义:

class Infant {
    constructor() {
        this.age  = 0;
        this.color = 'pink';
        this.food = 'milk';
    }

    eat() {
        return /*...something...*/;
    }
}

class Adolescent extends Infant {            // extends does #1 and #2
    constructor() {
        super();                             // #3, you can pass args here if appropriate

        this.age = 5;
        this.height = 'short';
        this.job = 'keep on growing';
    }
}