js 访问器
访问器用于设置和获取对象的私有属性,并且在设置或获取属性值时可以做其他操作
如下示例代码
就可以动态获取人的年龄,而且年龄只能根据生日计算得出,不需要也不能手动设置
class Person {
constructor(name) {
this.name = name
}
get birthday() {
return this.birthday_
}
set birthday(birthday) {
this.birthday_ = birthday
}
get age() {
return new Date().getFullYear() - this.birthday_.getFullYear()
}
}
let person = new Person('Jack')
person.birthday = new Date('2018-03-01')
console.log(`生日:${person.birthday}`);
console.log(`年龄:${person.age}`);
控制台输出
生日:Thu Mar 01 2018 08:00:00 GMT+0800 (中国标准时间)
年龄:3