通过 getters/setters 来截取对对象成员的访问。 它能帮助你有效的控制对对象成员的访问
class Person{
firstName:string;
lastName:string;
constructor(firstName:string,lastName:string){
this.firstName=firstName;
this.lastName=lastName;
}
get fullName(){
return this.firstName+'_'+this.lastName
}
set fullName(val){
let arr=val.split('_');
this.firstName=arr[0];
this.lastName=arr[1];
}
}
var a=new Person('东方','不败')
console.log(a.fullName)
a.fullName='西方_吹雪'
console.log(a)
当获取实例a的fullName时,它会根据fullName的get方法返回一个值
当设置实例a的fullName时,它会根据fullName的set方法去设置firstName和lastName