ES5和ES6继承的区别

493 阅读1分钟

ES5继承 --- 原型链继承

    // 定义父类
    function Parent(name) {
        this.name = name;
    }

    Parent.prototype.getName = function() {
        return this.name;
    };

    // 定义子类
    function Children() {
        this.age = 27;
    }

    // 通过Children的prototype属性和Parent进行关联继承

    Children.prototype = new Parent('王先生'); 

    // Children.prototype.constructor === Parent.prototype.constructor = Parent

    var test = new Children();

    // test.constructor === Children.prototype.constructor === Parent

    test.age // 27
    test.getName(); // 王先生

ES6 extends继承

    // 定义父类
    class Father {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }

        show() {
            console.log(`我叫:${this.name}, 今年${this.age}岁`);
        }
    };

    // 通过extends关键字实现继承
    class Son extends Father {};

    let son = new Son('王先生', 9000);
    
    son.show(); // 我叫王先生 今年9000岁

继承原理图解