JS笔记:ES6 Class

基本使用

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

  get x() {
    return this.x;
  }

  get y() {
    return this.y;
  }

  static distance(a, b) {
    const dx = a.x - b.x;
    const dy = a.y - b.y;

    return Math.hypot(dx, dy);
  }
}

const p1 = new Point(5, 5);
const p2 = new Point(10, 10);

console.log(Point.distance(p1, p2));

主意事项

  • ES6不支持private, public变量和函数,只有Typescript才有。
  • 所有的ES6 class variable都在constructor里面用this.myVarName起始。
  • 不支持function语法,写函数直接用函数名。
  • 支持static函数,支持gettersetter,语法如上。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容