ES6 笔记 Class和继承

定义class

class Point {
  //optional, 如果没写,相当于写了空的构造函数
  constructor(x, y) {
    this.x = x; //实例属性
    this.y = y; 
  }

  //定义在构造方法的prototype上
  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }

  //get 方法
  get propName() { ... }

  //set方法 
  set propName(arg) { ... }

  //方法名由变量生成
  [functionThatReturnsPropertyName()] (args) { ... }

  //定义在构造方法上
  static draw(circle, canvas) {
      // Canvas drawing code
  };
  
  //定义在构造方法上
  static get circlesMade() {
      return !this._count ? 0 : this._count;
  };
}

通过extend来继承父类的属性和方法

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

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

Mix

mix允许继承多个类的属性(实例属性和prototype属性)

class DistributedEdit extends mix(Loggable, Serializable) {
  // ...
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容