本文最后更新于:2024年4月25日 上午
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');
|
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]);
|
添加方法/属性
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])
|
属性拦截器
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)
|
静态属性
私有方法/属性
继承