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

Grasping prototypical Inheritance through pseudoclassical instantiation (JavaScript)

本文关键字:掌握 原型 继承 JavaScript 经典 实例化      更新时间:2023-09-26

我正在尝试通过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';
};

我想继承婴儿班的食物属性和吃法,但我的尝试失败了。 我最初的想法是分配这个。青少年=婴儿食品;但这没有用。我知道我需要将婴儿设置为超级类,但我正在旋转我的轮子

在 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 中添加的,因此它不会出现在过时的 JavaScript 引擎(如 IE8 中的引擎(上。不过,上面使用的单参数版本可以很容易地填充。

在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';
    }
}