特点:
- 监视某个属性,在他的值被读取和修改时分别调用对应的函数(get和set)
实例:
class Car{
name:string
price:number
constructor(name:string,price:number){
this.name = name
this.price = price
}
get Info(){
console.log('有人读取Info属性了');
return this.name+'_'+this.price
}
set Info(value){
console.log('有人修改Info属性了');
let tmp = value.split('_')
this.name = tmp[0]
this.price = Number(tmp[1])
}
}
let car= new Car('奔驰',100) // 实例化对象
car.Info // 有人读取Info属性了
car.Info = '保时捷_200' // 有人修改Info属性了