JavaScript 类实质上是 JavaScript 现有的基于原型的继承的语法糖。类语法不会为JavaScript引入新的面向对象的继承模型。
一、定义类:
类实际上是个“特殊的函数”,类语法有两个组成部分:类表达式(类声明)和类声明。
1.类声明
要声明一个类,使用带有class关键字的类名(此处类名是:Rectangle )。
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
提升问题:函数声明和类声明之间的一个重要区别是函数声明会提升,类声明不会。需要声明类,然后访问它,否则会抛出一个ReferenceError:
let p = new Rectangle();
// ReferenceError
class Rectangle {}
2.类表达式
类表达式可以是被命名的或匿名的。
/* 匿名类 */
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
/* 命名的类 */
let Rectangle = class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
};
二、构造函数和方法
1.构造函数
constructor方法用于创建和初始化一个由class创建的对象。一个类只能有一个 “constructor”方法。
一个构造函数可以使用 super 关键字来调用一个父类的构造函数。
2.原型方法
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
3.静态方法
static 关键字用来定义一个类的一个静态方法,调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。
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;
// console.log(dx, dy);//-5 -5
return Math.hypot(dx, dy); //对于给定的直角三角形的两个直角边,求其斜边
}
}
const p1 = new Point(5, 5);
const p2 = new Point(10, 10);
// console.log(p1);//Point { x: 5, y: 5 }
console.log(Point.distance(p1, p2)); //7.0710678118654755
4.实例属性:
实例的属性必须定义在类的方法里:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
静态的或原型的数据属性必须定义在类定义的外面。
Rectangle.staticWidth = 20;
Rectangle.prototype.prototypeWidth = 25;