类
为了和其他语言形态一致,ES6提供了class 关键词作为原型链继承的语法糖来模拟其他主流语言中的类的继承形态,简化了原型的定义的过程。
- class只是JS提供的一个语法糖,优化并且简化了原型继承
- class 语法定义的成员间无需使用逗号
- 类的本质是函数
- 类的属性可以定义在构造函数中也可以直接定义在class中
- 定义在类中的属性无需使用
this
,方法无需使用this
和function
,直接使用方法签名+()
的形式 - class 中定义的方法直接定义在其原型中且不能枚举
- class 默认使用strict 严格模式执行
- 使用
static
关键字设置静态属性和静态方法 - 类中可以使用
set
和get
访问器对属性进行访问控制 - class中使用
extends
关键字进行 继承 super
指向上一基类,定义构造函数必须优先调用super()
以调用基类构造
定义语法
定义一个类User
,注意类的定义中,成员之间无需逗号分隔,这点与原型不同。constructor
对象指向其构造函数,this
指向其实例对象本身。
class User{
constructor(name){
this.name = name;
this.show = function(){
console.log("User -> " + this.name)
}
}
//无需逗号
getName(){
return this.name;
}
}
使用new
关键字创建一个实例对象,constructor
会在 new
时自动执行
let lisi = new User("lisi");
类的本质是一个函数对象,所以可以跟构造方法一样使用new关键字调用其constructor
创建实例对象
console.log(User.__proto__) // function()
所以下面的两段代码的实现效果是一样的
class User {
constructor(name){
this.name = name;
}
getName() {
return this.name;
}
}
function User(name){
this.name = name;
}
User.prototype.getName = function(){
return this.name;
}
定义属性
类的属性定义有如下两种方法,可以定义在构造函数中也可以直接定义在类中,定义在类中的属性无需使用this
和function
定义,直接使用方法签名+()
的形式,定义在
class User{
constructor(){
this.age = 20;
this.func1 = function(){
return "func1()";
}
}
name = "张三";
func3(){
return "func3";
}
}
class 中定义的方法直接定义在其原型中且不能枚举
class User {
constructor(name) {
this.name = name;
}
func() {
console.log("func");
}
}
User.prototype.func(); // func
let pd = Object.getOwnPropertyDescriptor(User.prototype,"func");
console.log(pd.enumerable); // false
静态属性
静态属性即为类设置属性,而不是为生成的对象设置,在JS中使用static
关键字设置
class User{
constructor(){};
static name = "User's name";
}
let john = new User();
console.log(john.name);//undefined
console.log(User.name);//User's name
静态方法
与静态属性类似,指通过类访问而不能通过实例对象访问的方法
class User{
constructor(){
};
static name = "User's name";
static show(){
console.log(this.name);
}
}
let john = new User();
User.show(); // User's name
john.show(); // 报错!! 方法不存在
访问器
使用访问器可以对对象的属性进行访问控制
class User {
constructor(name, age) {
this.data = { name, age }
}
set age(value) {
if (typeof value != Number || value <= 0)
console.error("年龄不合法");
this.data.age = value;
}
get age() {
return this.data.age;
}
}
let peter = new User("peter",20);
peter.age = -20; // 报错 : 年龄不合法
继承
使用 extends
关键字进行 继承,super
指向上一基类构造,在定义constructor
时必须优先调用父类构造,即super()
class Preson{
constructor(name,age){
this.name = name;
this.age = age;
}
show(){
console.log(`${this.name} ${this.age}`);
}
}
class User extends Preson{
constructor(name,age,sex){
super(name,age);
this.sex = sex
}
UserShow(){
console.log(`${this.name} ${this.age} ${this.sex}`);
}
}
let user = new User("张三",20,"男");
user.show();//张三 20
user.UserShow();//张三 20 男