你真的了解Class继承吗?(es6)

ES6总结系列之 Class的继承 篇

ES6之前我们经常通过修改原型链的方法来实现继承,ES6的 Class 提供了更为便利、清晰的方法来实现继承,让我们来看下吧

1. 基本用法

通过 extends 关键字来实现继承

class Point { /* ... */ }

class ColorPoint extends Point {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }

  toString() {
    return this.color + ' ' + super.toString(); // 调用父类的toString()
  }
}

2. 注意要点

  1. 子类的构造函数 construtor 方法中必须调用 super 方法,否则会报错
class Point { /* ... */ }

class ColorPoint extends Point {
  constructor() {
  }
}

let cp = new ColorPoint(); // ReferenceError

原因是子类自己的 this 对象,必须先通过父类的构造函数完成构造

  1. 子类的构造函数中,只有调用了 super 之后,才可以使用 this,否则会报错

  2. 父类的静态方法,也会被子类继承

class A {
  static hello() {
    console.log('hello world');
  }
}

class B extends A {
}

B.hello()  // hello world

3. super 关键字

super 关键字既可以当函数使用,也可以当做对象使用

  1. 当函数使用时,代表父类的构造函数,且只能用在子类的构造函数中,用在其他地方会报错
class A {}

class B extends A {
  constructor() {
    super();
  }
}
  1. 当函数使用时 super 内部的 this 指的是B的实例

super 虽然代表了父类A的构造函数,但是返回的是子类B的实例

  1. super 作为对象的时,指向父类的原型对象
class A {
  constructor() {
    this.p = 2;
  }
}

class B extends A {
  get m() {
    return super.p;
  }
}

let b = new B();
b.m // undefined

由于 super 指向父类的原型对象,所以取不到定义在父类实例上的方法或属性

  1. super作为对象,用在静态方法之中,这时super将指向父类,而不是父类的原型对象。
class Parent {
  static myMethod(msg) {
    console.log('static', msg);
  }

  myMethod(msg) {
    console.log('instance', msg);
  }
}

class Child extends Parent {
  static myMethod(msg) {
    super.myMethod(msg);
  }

  myMethod(msg) {
    super.myMethod(msg);
  }
}

Child.myMethod(1); // static 1

var child = new Child();
child.myMethod(2); // instance 2

4.类的 prototype 属性和__proto__属性

  1. 类的 __proto__ 属性,表示构造函数的继承,总是指向父类

  2. 子类的 prototype 属性的 __proto__ 属性,表示方法的继承,总是指向父类的 prototype

class A {
}

class B extends A {
}

B.__proto__ === A // true
B.prototype.__proto__ === A.prototype // true

类的继承的实现模式

class A {
}

class B {
}

// B 的实例继承 A 的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// 等同于B.prototype.__proto__ = A.prototype;

// B 继承 A 的静态属性
Object.setPrototypeOf(B, A);
// 等同于B.__proto__ = A;

const b = new B();

总结

  1. 子类的构造函数 construtor 方法中必须调用 super 方法,否则会报错
  2. 子类的构造函数中,只有调用了 super 之后,才可以使用 this,否则会报错
  3. 父类的静态方法,也会被子类继承
super 关键字
  1. super 作为函数时,代表父类的构造函数,且只能用在子类的构造函数中,用在其他地方会报错
  2. super 作为函数时, super 内部的 this 指的是B的实例
  3. super 作为对象时,指向父类的原型对象
  4. super 作为对象时,用在静态方法之中,这时super将指向父类,而不是父类的原型对象。
类的 prototype 属性和__proto__属性
  1. 类的 __proto__ 属性,表示构造函数的继承,总是指向父类

  2. 子类的 prototype 属性的 __proto__ 属性,表示方法的继承,总是指向父类的 prototype


  • 个人Github,欢迎star^_^
  • ES6总结系列参考自阮一峰《ECMAScript6入门》
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值