最近刚刚发现关于对类属性使用 get 和 set 关键字我想知道在 typescript 类中使用 get/set 时的首选方法是什么:
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;
}
}
我只是好奇是否有任何最佳实践、性能或其他因素。
最佳答案
Getter 和 Setter 有多种用途,例如
You can make a private variable read only, if you don't specify a setter
class example {
private _a: any;
get a(): any{
return this._a;
}
}
You can use them to execute a custom logic when a variable changes, sort of a replacement for Event Emitter
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
}
}
You can use them to alias an output
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";
}
}
}
A setter can be used for a clean assignment
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
}
}
Finally setter's biggest strength is the ability to check variables for proper value before assignment
class Hero {
private _age: number;
set age(age: number) {
if (age > 0 && age < 100) {
this._age = age
} else {
throw SomeError;
}
}
}
关于angular - typescript - 什么是更好的 : Get/Set properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49053103/