JavaScript 中的继承

ES5

在 ES6 class 出现以前,JavaScript 实现继承是通过 prototype 原型来实现的。将子类对象的原型指向父类对象的原型。
Son.prototype.__proto__ = Parent.prototype
代码模拟继承的实现如下:

function Human(name){
    this.name = name;
}
Human.prototype.run = function(){};
function Man(name){
    Human.call(this, name);
    this.gender = 'male';
}
Man.prototype.__proto__ = Human.prototype;

然而 IE 不支持Man.prototype.__proto__ = Human.prototype,解决方案如下:

let f = function(){};
f.prototype = Human.prototype;
Man.prototype = new f();

ES6

ES6 中新添了 class 继承的语法糖,本质上还是基于原型的继承。
代码如下:

class Human{
    constructor(name){
        this.name = name;
    };
    run(){};
}

class Man extends Human{
    constructor(name){
        super(name);
        this.gender = 'male';
    }
}

你可能感兴趣的:(JavaScript 中的继承)