js 中的class
类声明
需要声明一个类,需要使用class
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
和函数声明的最大的区别在于,类声明,不会出现声明提前,函数声明会出现声明提前,这是两者最大的区别。
在上方中,声明类以后,新建一个对象
let rectAngle = new Rectangle
该对象具有constructor方法。
匿名类
和匿名函数类似,类依旧可以进行匿名声明
let Rectangle = class {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
在类表达式中,同样会出现类声明提升的问题。
constructor
为一个构造函数,用于初始化class并创建一个对象
即为原先学习的构造函数,函数为对象,对象为函数。
class Rectangle {
// 构造函数
constructor(height, width) {
this.height = height;
this.width = width;
};
// get 方法即调用将会返回的值
get area() {
return this.calcArea();
};
// 定义calcArea函数
calcArea() {
return this.height * this.width;
}
}
上方定义了一个类如果需要使用
const square = new Rectangle();
console.log(square.area);
即可完成对类的使用。