🟡ES6类

本文最后更新于:2023年7月28日 凌晨

class关键字声明类,new关键字创建新的类实例

contructor

contructor(x, y, ...)生成类实例时该方法就会执行

1
2
3
4
5
6
7
8
class Info {
constructor (name) {
console.log(`New Info Class: ${name} Created`)
}
}

const info = new Info('Info');
// > New Info Class: Info Created

contructor()默认返回this将实例暴露出来,若返回一个非原始类型时外部就得不到对象实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Info {
constructor (name) {
console.log(`New Info Class: ${name} Created`)
return {}
}
}

const info = new Info('Info');

console.log([info, info instanceof Info]);

/**
* New Info Class: Info Created
* [ {}, false ]
*/

添加方法/属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Person {
constructor (name, age) {
this.name = name
this.age = age
}

about () {
console.log(`${this.name} is ${this.age} years old`)
}
}

const me = new Person('Jonathan', 20)

me.about()
console.log([me.name, me.age])
/**
* Jonathan is 20 years old
* ['Jonathan', 20]
*/

属性拦截器

class使用get,set关键字定义属性拦截器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Student {
static gradeType = ['A', 'B', 'C', 'D', 'F']

constructor (name, age, gradeCode) {
this.name = name
this.age = age
this.grade = gradeCode
}

get grade () {
return this.gradeName
}

set grade (value) {
this.gradeName = this.gradeType[value]
}
}

const student = new Student('Jonathan', 20, 1)

console.log(student.grade)

静态属性

私有方法/属性

继承


🟡ES6类
https://qingshaner.com/ES6类/
作者
清山
发布于
2022年2月3日
许可协议