在调用启动时,只需通过绕过setter和getter函数来初始化属性值:
export class Example {
private _value: number = 0;
set value(newVal) {
// Your setter logic here
this._value = newVal;
}
get value() {
// Your getter logic here
return this._value;
}
constructor() {
// Initialize your object without calling the value setter method
this._value = 42;
}
public doSomething() {
// Use your getter method without the overhead of first calling your setter method
console.log(this.value);
}
}
由于我们仅在构造函数中执行了_value的初始化,而没有显式调用setter方法,因此它将绕过setter方法。这意味着您的setter方法将始终仅在请求更新属性时运行,而不是在初始化属性时运行。