基础语法
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);
}
}
简写
class Note {
public title: string;
public content: string;
private history: string[];
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[]
){
}
}