Classes
类是用于创建对象的模板,JS 的类建立在原型上
定义类
类声明
class Rectangle {constructor(height, width) {this.height = height;this.width = width;}}
使用
let p = Rectangle();
类声明与函数声明的不同:函数申明会提升,类声明不会,必须先声明再使用,否则报错 ReferenceError
类表达式
定义类的另一种方法,可以命名或不命名
// 未命名/匿名类let Rectangle = class {constructor(height, width) {this.height = height;this.width = width;}};console.log(Rectangle.name); // "Rectangle"// 命名类let Rectangle = class Rectangle2 {constructor(height, width) {this.height = height;this.width = width;}};console.log(Rectangle.name); // "Rectangle2"
方法定义
- 类体是
{}中的部分,可以在里面定义类的方法或构造函数 - 类声明和类表达式的主体都执行在严格模式下,如构造函数,静态方法,原型方法,getter和setter都在严格模式下执行。
- 构造函数:用于创建和初始化由 class 创建的对象,每个 class 只能由一个,一个构造函数可以用 super 关键字来调用一个父类构造函数
原型方法
```javascript class Rectangle { // constructor constructor(height, width) {
} // Getter get area() {this.height = height;this.width = width;
} // Method calcArea() {return this.calcArea()
} } const square = new Rectangle(10, 10);return this.height * this.width;
console.log(square.area); // 100
<a name="WAlGt"></a>### 静态方法```javascriptclass 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);p1.displayName; // undefinedp1.distance; // undefinedconsole.log(Point.displayName); // "Point"console.log(Point.distance(p1, p2)); // 7.0710678118654755
属性
实例属性定义在类的方法里,静态或原型的属性定义在类定义的外面
class Rectangle {constructor(height, width) {// 实例上的属性this.height = height;this.width = width;}}// 静态属性Rectangle.staticWidth = 20;// 原型上的属性Rectangle.prototype.prototypeWidth = 25;
extend
继承
如果子类中定义了构造函数,那么它必须先调用 super() 才能使用 this
class Animal {constructor(name) {this.name = name;}speak() {console.log(`${this.name} makes a noise.`);}}class Dog extends Animal {constructor(name) {super(name); // 调用超类构造函数并传入name参数}speak() {console.log(`${this.name} barks.`);}}var d = new Dog('Mitzie');d.speak();// 'Mitzie barks.'
super
用于调用父类上的函数
class Cat {constructor(name) {this.name = name;}speak() {console.log(this.name + ' makes a noise.');}}class Lion extends Cat {speak() {super.speak();console.log(this.name + ' roars.');}}
