定義class
class Point {
//optional, 如果沒(méi)寫(xiě),相當(dāng)于寫(xiě)了空的構(gòu)造函數(shù)
constructor(x, y) {
this.x = x; //實(shí)例屬性
this.y = y;
}
//定義在構(gòu)造方法的prototype上
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
//get 方法
get propName() { ... }
//set方法
set propName(arg) { ... }
//方法名由變量生成
[functionThatReturnsPropertyName()] (args) { ... }
//定義在構(gòu)造方法上
static draw(circle, canvas) {
// Canvas drawing code
};
//定義在構(gòu)造方法上
static get circlesMade() {
return !this._count ? 0 : this._count;
};
}
通過(guò)extend
來(lái)繼承父類(lèi)的屬性和方法
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 調(diào)用父類(lèi)的constructor(x, y)
this.color = color; //必須先調(diào)用父類(lèi)的constructor扣甲,才能使用this
}
toString() {
return this.color + ' ' + super.toString(); // 調(diào)用父類(lèi)的toString()
}
}
Mix
mix允許繼承多個(gè)類(lèi)的屬性(實(shí)例屬性和prototype屬性)
class DistributedEdit extends mix(Loggable, Serializable) {
// ...
}