class Polygon {
constructor(width, height) {
console.log("first!");//調用靜态方法時,constructor 并沒有執行
this.width = width;
this.height = height;
this.name = "Polygon";
}
//為屬性添加 getter
get area() {
return this.square || this.width * this.height;
}
//為屬性添加 setter
set area(square) {
this.square = square;
}
//執行個體方法
sayName() {
console.log(this.name);
//this.hello();//靜态方法不能直接在非靜态方法中使用 this 關鍵字來通路
this.constructor.hello();//可以使用 this.constructor.STATIC_METHOD_NAME()
Polygon.hello();//還可以直接使用 CLASSNAME.STATIC_METHOD_NAME()
}
static hello() {
console.log("hello." + this.name);//靜态方法中可以使用 this 調用屬性,會使用 constructor 中預設值
//this.sayName();//但不可以使用 this 調用非靜态方法,靜态方法中,不可以調用執行個體方法
}
static say() {
this.hello();//在同一個類中的一個靜态方法調用另一個靜态方法,你可以使用 this 關鍵字
}
}
class Square extends Polygon{
constructor(length) {
super(length, length);
this.name = "Square";
}
set area(square) { // 重名方法會覆寫
this.square = square;
this.width = this.height = Math.sqrt(square);
}
}
Polygon.say();
let a = new Polygon(, );
a.sayName();
console.log(a.width, a.height, a.square, a.name);
Square.hello();
let b = new Square();
b.area = ;
b.sayName();
console.log(b.width, b.height, b.square, b.name);
/*
hello.Polygon
first!
Polygon
hello.Polygon
hello.Polygon
2 3 undefined 'Polygon'
hello.Square
first!
Square
hello.Square
hello.Polygon
4 4 16 'Square'
*/