Class 的继承

Class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要清晰和方便很多。

class Point {
  constructor(x,y){
    this.x = x;
    this.y = y ;
    this.prop = 'prop';
  }
  static staticMethod(){
    return 'static method'
  }
  toString(){
    return 'x:'+this.x +',y:'+this.y;
  }
  _privateMethod(){
    
  }
}
class ColorPoint extends Point{
  constructor(color,x,y){
    super(x,y);
    this.color = color;
  }
  toString(){
    console.log('color:'+this.color+","+super.toString())
  }
}
var colorPoint = new ColorPoint('red',1,10);
colorPoint.toString();//"color:red,x:1,y:10"

constructor方法和toString方法之中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。
另一个需要注意的地方是,在子类的构造函数中,只有调用super之后,才可以使用this关键字,否则会报错。这是因为子类实例的构建,是基于对父类实例加工,只有super方法才能返回父类实例

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

class ColorPoint extends Point {
  constructor(x, y, color) {
    this.color = color; // ReferenceError
    super(x, y);
    this.color = color; // 正确
  }
}

最后,父类的静态方法,也会被子类继承。

console.log(ColorPoint.staticMethod())//"static method"

Object.getPrototypeOf()
Object.getPrototypeOf方法可以用来从子类上获取父类

console.log(Object.getPrototypeOf(ColorPoint)===Point)//true

super 关键字
super这个关键字,既可以当作函数使用,也可以当作对象使用。在这两种情况下,它的用法完全不同。

第一种情况,super作为函数调用时,代表父类的构造函数。ES6 要求,子类的构造函数必须执行一次super函数。

class A {
  constructor() {
    console.log(new.target.name);
  }
}
class B extends A {
  constructor() {
    super();
  }
}
new A() // A
new B() // B

第二种情况,super作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。

class A {
  p() {
    return 2;
  }
}

class B extends A {
  constructor() {
    super();
    console.log(super.p()); // 2
  }
}

let b = new B();

ES6 规定,通过super调用父类的方法时,方法内部的this指向子类。

class A {
  constructor() {
    this.x = 1;
  }
  print() {
    console.log(this.x);
  }
}

class B extends A {
  constructor() {
    super();
    this.x = 2;
  }
  m() {
    super.print();
  }
}

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

类的 prototype 属性和proto属性
大多数浏览器的 ES5 实现之中,每一个对象都有proto属性,指向对应的构造函数的prototype属性。Class 作为构造函数的语法糖,同时有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之间可以通过extends关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多...
    庸者的救赎阅读 438评论 0 2
  • class的基本用法 概述 JavaScript语言的传统方法是通过构造函数,定义并生成新对象。下面是一个例子: ...
    呼呼哥阅读 4,128评论 3 11
  • 本文先对es6发布之前javascript各种继承实现方式进行深入的分析比较,然后再介绍es6中对类继承的支持以及...
    lazydu阅读 16,727评论 7 44
  • 第一次到昆明,先是看世博园。 昆明这座西南名城也确实是借园艺世博会的机会好好地把城市面貌打造了一下,否则可能还一直...
    0538d64591d8阅读 210评论 0 0
  • 文/孤鸟差鱼 可以没有南瓜和马车 也无需王子和灰姑娘 只盼尘世两人 还能看对眼 纯粹是喜欢
    孤鸟差鱼阅读 171评论 5 3