技术/前端/ECMAScript

class的继承通过extends关键词实现,具体继承关系如下图所示:

Animal

  1. class Animal {
  2. constructor(name) {
  3. this.speed = 0;
  4. this.name = name;
  5. }
  6. run(speed) {
  7. this.speed += speed;
  8. alert(`${this.name} runs with speed ${this.speed}.`);
  9. }
  10. stop() {
  11. this.speed = 0;
  12. alert(`${this.name} stands still.`);
  13. }
  14. }
  15. let animal = new Animal("My animal");

QQ20190807-145141.png

Rabbit

class Rabbit {
  constructor(name) {
    this.name = name;
  }
  hide() {
    alert(`${this.name} hides!`);
  }
}

let rabbit = new Rabbit("My rabbit");

QQ20190807-145229.png

可以通过extendsRabbit继承Animal

class Rabbit extends Animal {
    hide() {}
}

这样Rabbit可以继承Animalrunstop方法。
在内部,extends会给Rabbit.prototype增加[[Prototype]],指向Animal.prototype

QQ20190807-145746.png

ES6具体实现是使用Object.setPrototypeOf方法

Object.setPrototypeOf = function (obj, proto) {
  obj.__proto__ = proto;
  return obj;
}

实现基础:

// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);

// B 继承 A 的静态属性
Object.setPrototypeOf(B, A);

const b = new B();

ES5实现继承:

function Super() {}
function Sub() {}

Sub.prototype = new Super();
Sub.prototype.constructor = Sub;

var sub = new Sub();

ES5实现继承和ES6中的继承基本一致,只有一些不同。ES6中的子类和父类也会通过__proto__链接。
1959053-5e1363db5a125d1f.webp

原文地址-Class inheritance
Class的继承