类语法

4 阅读1分钟

基础语法

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

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

实例属性的新写法

// 原来的写法
class IncreasingCounter {
  constructor() {
    this._count = 0;
  }
  get value() {
    return this._count;
  }
  increment() {
    this._count++;
  }
}
class IncreasingCounter {
  _count = 0;
  get value() {
    return this._count;
  }
  increment() {
    this._count++;
  }
}

静态方法

class Foo {
  static classMethod() {
    return 'hello';
  }
}

静态属性

class MyClass {
  static myStaticProp = 42;

  constructor() {
    console.log(MyClass.myStaticProp); // 42
  }
}

简写

class Note { 
  public titlestring; 
  public contentstring; 
  private historystring[]; 
   
  constructor(title: string, content: string, history: string[]) { 
    this.title = title; 
    this.content = content; 
    this.history = history; 
     
  } 
}
class Note { 
  constructor( 
     public title: string,  
     public content: string,  
     private history: string[] 
  ){ 
    // 这里不用在写 this.title = title 
  } 
}