class Animal {
speak() {
return this;
}
static eat() {
return this;
}
}
let obj = new Animal();
console.log(JSON.stringify(obj.speak()))
let speak = obj.speak;
console.log(JSON.stringify(speak()))
console.log(JSON.stringify(Animal.eat()))
let eat = Animal.eat;
eat();
console.log(JSON.stringify(eat()))
// 静态方法 static 关键字用来定义一个类的一个静态方法。
// 调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。
// 静态方法通常用户为一个应用程序创建工具函数。
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.y;
const dy = a.y - b.y;
return Math.hypot(dx, dy);
}
}
const p1 = new Point(5, 5)
const p2 = new Point(10, 10);
console.log(Point.distance(p1, p2));
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea()
}
calcArea() {
console.log(this.width)
return this.height * this.width;
}
}
const square = new Rectangle(10, 100);
console.log(square.area);
console