代码之家  ›  专栏  ›  技术社区  ›  rory-h

JS继承刷新器-ES6+[复制]

  •  0
  • rory-h  · 技术社区  · 6 年前

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

    我想继承婴儿班的食物财产和饮食方法,但我的尝试失败了。我最初的想法是这个。青少年= 婴儿食品但那没用。我需要知道我的婴儿车,但我要知道我的婴儿

    0 回复  |  直到 9 年前
        1
  •  6
  •   T.J. Crowder    4 年前

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

    1. 使 prototype 原型

    2. 设置 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引擎上。上面使用的单参数版本可以是 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';
        }
    }
    
    推荐文章