通过伪经典实例化(JavaScript)抓取原型继承

时间:2016-01-06 09:06:42

标签: javascript inheritance prototype decorator prototypal-inheritance

我试图通过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';

};

我想继承婴儿班的食物和吃法,但我的尝试不足。我最初的想法是分配这个.Adolescent = Infant.food;但那并没有奏效。我知道我需要将婴儿设置为超级课程,但我要旋转我的轮子

1 个答案:

答案 0 :(得分:4)

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

  1. 制作"派生"的prototype属性构造函数一个对象,其原型是" base"的prototype属性。构造

  2. 在"派生"上设置constructor属性构造函数的prototype属性指向"派生的"构造

  3. 拨打" base"构造函数来自"派生"具有正确this

  4. 的构造函数

    像这样:

    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
    Adolescent.prototype.constructor = Adolescent;          // #2
    
    在ES5中添加了

    Object.create,因此它不会出现在IE8中过时的JavaScript引擎上。上面使用的单参数版本可以是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';
        }
    }