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(2, 3);
a.sayName();
console.log(a.width, a.height, a.square, a.name);
Square.hello();
let b = new Square(5);
b.area = 16;
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'
*/
ES6 class extends
最新推荐文章于 2024-06-24 14:58:06 发布