js中的继承

js中的继承在es5中有很多种方式,让人眼花缭乱。那么今天我们就来统一一下,找到一个相对来说,最理想的方案(寄生组合式)来解决这个问题吧:

function Father (name) {
    this.name = name;
}

Father.prototype.sayName = function () {
    console.log(this.name);
}

function Child (name, age) {
    Father.call(this, name);
    this.age = age;
}

Child.prototype = Object.create(Father.prototype);
Child.prototype.constructor = Child;

Child.prototype.sayAge = function () {
    console.log(this.age);
}

es6已经解决了这个问题,采用babel转码后的工程即可支持如下的es6写法:

class Father {
    constructor (name) {
        this.name = name
    }
    
    sayName () {
        console.log(this.name);
    }
}

class Child extends Father {
    constructor (name, age) {
        super(name);
        this.age = age;
    }

    sayAge () {
        console.log(this.age);
    }
}

ok,喜欢的同学可以收藏一下了。

posted @ 2019-07-15 17:48  拿饭盒当烟灰缸  阅读(137)  评论(0编辑  收藏  举报