类Class
类语法(类表达式和类声明)
类声明 (类声明不会声明提前)
constructor方法是一个特殊的方法,其用于创建和初始化使用class创建的一个对象,一个类只能有一个名为constructor的特殊方法,因此需要初始化数据的在这里直接先定义,
1 声明方式
class SHUEN{
constructor(h,w){this.height=h;this.width=w;}
}
2 类必须先声明再使用,
类表达式(另一种声明方式,会声明提前)
/*匿名*/
let shuen=class{
constructor(h,w){...}
}
/*命名的类*/
let shuen=class shuen{constructor(h,w){...}}
3 原型方法
class Rectangle {
// constructor
constructor(height, width) {
this.height = height;//相当于定义变量
this.width = width;
}
// Getter
get area() {
return this.calcArea()
}
// Method
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area);
// 100
4 静态方法
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static distance(a, b) {
const dx = a.x - b.x;
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));
5 用原型和静态方法包装

浙公网安备 33010602011771号