刚刚发现关于为类属性使用get和set关键字我想知道在使用get / set for typescript类时首选方法是什么:
class example {
private a: any;
private b: any;
getA(): any{
return this.a;
}
setA(value: any){
this.a = value;
}
get b(): any{
return this.b;
}
set b(value: any){
this.b = value;
}
}
我很好奇是否有最佳做法,表现或其他因素。
答案 0 :(得分:9)
Getter和Setters有多种用途,例如
如果您没有指定设置者
,则可以将私有变量设为只读
class example {
private _a: any;
get a(): any{
return this._a;
}
}
当变量发生变化时,您可以使用它们来执行自定义逻辑,排除事件发射器的替代
class example {
private _a: any;
set a(value: any){
this._a = value;
// Let the world know, I have changed
this.someMethod();
}
someMethod() {
// Possibly a POST API call
}
}
您可以使用它们来对输出进行别名
class Hero {
private _health: any = 90;
get health(): string {
if(this._health >= 50) {
return "I am doing great!";
} else {
return "I don't think, I'll last any longer";
}
}
}
可以使用setter进行清洁分配
class Hero {
private _a: number;
set a(val: number) {
this._a = val;
}
setA(val: number) {
this._a = val;
}
constructor() {
this.a = 30; // Looks cleaner
this.setA(50); // Looks Shabby, Method's purpose is to perform a logic not handle just assignments
}
}
最后,setter的最大优势是能够在分配之前检查变量的正确值
class Hero {
private _age: number;
set age(age: number) {
if (age > 0 && age < 100) {
this._age = age
} else {
throw SomeError;
}
}
}