Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
// 1. 类声明
let User = class {
// 构造函数:声明属性
constructor(uname, email) {
// (1) 属性
this.uname = uname
this.email = email
}
// (2) 方法
say() {
return `${this.uname}: ( ${this.email} )`
}
// (3) 静态成员
static nation = 'CHINA'
}
// 2. 类的实例化
const user = new User('潘金莲', 'pjl@qq.com')
console.log(user.say())
console.log(User.nation)
console.log('-----------------------')
// ? 继承
class Child extends User {
constructor(uname, email, sex) {
// super 调用父类成员
super(uname, email)
// 子类扩展的属性
this.sex = sex
}
say() {
// super.say() 父类中的say()
return `${super.say()}, (${this.sex})`
}
}
const child = new Child('灭绝', 'mj@qq.com', '女')
console.log(child.say())
// ! 在类中使用"访问器属性"
const Stu = class {
// 私有属性: 在属性前加 #
#age = 18
// 访问器属性
// 1. 读, 获取器get
get age() {
return this.#age
}
// 2. 写, 设置器 set
set age(age) {
if (age >= 18 && age <= 100) {
this.#age = age
} else {
console.log('年龄必须在18-100之间')
}
}
}
let stu = new Stu()
console.log('age = ', stu.age)
// stu.age = 120
stu.age = 30
console.log('age = ', stu.age)