类
类 ”特殊的函数“,就像定义函数表达式和函数声明一样。主要组成:类表达式和类声明。
1、类声明:
定义类的一种方法,声明一个类,使用带有class关键字的类名
class MyClass {
constructor(height, width){
this.height = height;
this.width = width;
}
}
提升:
函数声明和类声明的区别,在于函数声明会提升,类声明不会。如果你先访问类,会抛出错误
ReferenceError。
let name = new MyClass(); //ReferenceError
class MyClass {}
2、类表达式:
是定义类的另一种方法,可命名或不命名。
// 未命名/匿名类
let MyClass= class { constructor(height, width) {
this.height = height;
this.width = width;
}
};
// 命名类let MyClass2= class MyName{ constructor(height, width) {
this.height = height;
this.width = width;
}
};
类体和方法定义:
1、一个类的类体是一对花括号/大括号 {}
中的部分。
2、类声明和类表达式的主题都执行在严格模式下。
3、constructor方法是一个特殊的方法,这种方法用于创建和初始化一个由class
创建的对象。一个类只能拥有一个名为 “constructor”的特殊方法。如果类包含多个constructor
的方法,则将抛出 一个SyntaxError
。
原型方法:
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
静态方法:
[static](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes/static)
关键字用来定义一个类的一个静态方法
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
static displayName = "Point";
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);
p1.displayName;
// undefined
p1.distance;
// undefined
console.log(Point.displayName);
// "Point"
console.log(Point.distance(p1, p2));
// 7.0710678118654755