继承是面向对象编程语言的一个特性,子类继承父类的特征和行为,使得子类对象(实例)具有父类的实例域和方法,或子类从父类继承方法,使得子类具有父类相同的行为。而Js不是面向对象语言,但是可以通过原型来实现继承,在es5中,继承可以用寄生组合继承来实现。

寄生组合继承

寄生组合继承的实现主要有三步

  1. 子类实现父类的构造函数的属性和方法
  2. 子类的prototype__proto__指向父类的prototype
  3. 修改子类原型链上的constructor指向子类的构造函数

比如下面一个构造函数

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

Animal.prototype.say = function () {
    console.log(`I'm ${this.name}`);
};

let animal = new Animal('animal');
animal.say();

实现一个鸟继承自动物,根据上面的步骤

// 第一步
function Bird (name) {
    Animal.apply(this, arguments);
}
// 第二步
Bird.prototype = Object.create(Animal.prototype);
// 第三步
Bird.prototype.constructor = Bird;

let bird = new Bird('anger bird');
bird.say();

class实现继承

es6提供的类实际上是个“特殊的函数”,就像你能够定义的函数表达式和函数声明一样,类语法有两个组成部分:类表达式和类声明。可以用class来实现继承,例如上面的例子可以用es6来写

MDN指出,类语法不会为JavaScript引入新的面向对象的继承模型。

class Animal {
    constructor (name) {
        this.name = name;
    }
    say () {
        console.log(`I'm ${ this.name }`);
    }
}

let animal = new Animal('animal');
animal.say();

class Bird extends Animal {
    constructor (name) {
        super(name);
    }
}

let bird = new Bird('anger bird');

 

本文为原创,未经授权,禁止任何媒体或个人自媒体转载
商业侵权必究,如需授权请联系[email protected]
标签: Javascript