基本用法
- 作用相当于一个构造函数
- 通过关键词
class
来定义类/实现类的继承 - 静态属性的用关键字
static
修饰 -
constructor
为类的构造方法,会自执行 - 类的一般方法,相当于定义在实例对象的原型对象上
class Person {
// 类的静态属性,关键字static,给类自身添加属性
static staticFun = function() {
console.log('类的静态属性,关键字static,给类自身添加属性');
};
// constructor 类的构造方法,会自执行
constructor(name, age) {
console.log('执行类的构造方法');
this.name = name;
this.age = age;
}
/**
* 类的一般方法:
* 相当于定义在实例对象的原型对象上
* 即若Person为一个构造函数,则类的一般方法相当于 Person.prototype.showMsg
**/
showMsg() {
console.log(this.name, ' & ', this.age);
}
};


继承
- 通过关键词
extends
来实现类的继承 - 通过
super()
调用父类的构造方法 - 重写从父类继承的一般方法
// 父类复用上面的Person
// 子类
class childPerson extends Person {
constructor(name, age, sex) {
super(name, age); // 调用父类的构造方法
this.sex = sex;
}
// 直接重写一般方法
showMsg() {
console.log(this.name, ' & ', this.age, ' & ', this.sex);
}
}
let child1 = new childPerson('zhangsan', 50, '男');

另:若之前学习的构造函数的继承方式有所遗忘,可参考原型、原型链、及拓展(继承模式)
特点
参考:https://github.com/Advanced-Frontend/Daily-Interview-Question/issues/20
- class 声明会提升,但不会初始化赋值。(类似于 let、const 声明变量;)
- class 声明内部会启用严格模式;
- class 的所有方法(包括静态方法和实例方法)都是不可枚举的;
- class 的所有方法(包括静态方法和实例方法)都没有原型对象 prototype,所以也没有 [[constructor]],不能使用 new 来调用;
- 必须使用 new 来调用 class;
- class 内部无法重写类名;
网友评论