在 TypeScript 中,存取器(Accessors)是一种特殊的类成员,它包括 get 和 set 方法。它们用于控制对类属性的访问和赋值过程。 存取器的基本语法如下:
class ClassName {
private _property: type;
get property(): type {
// getter 方法
return this._property;
}
set property(value: type) {
// setter 方法
this._property = value;
}
}
在这个例子中:
下面是一个更加具体的示例:
class BankAccount {
private _balance: number = 0;
get balance(): number {
return this._balance;
}
set balance(amount: number) {
if (amount < 0) {
console.log("Invalid amount. Balance cannot be negative.");
} else {
this._balance = amount;
}
}
deposit(amount: number): void {
this.balance += amount;
}
withdraw(amount: number): boolean {
if (amount <= this.balance) {
this.balance -= amount;
return true;
} else {
return false;
}
}
}
let account = new BankAccount();
account.deposit(1000);
console.log(account.balance); // 输出: 1000
account.withdraw(500);
console.log(account.balance); // 输出: 500
account.balance = -100; // 输出: "Invalid amount. Balance cannot be negative."
在这个例子中:
通过使用存取器,我们可以在不破坏类 API 的情况下,对类属性的访问和赋值过程进行控制和验证。这有助于创建更加健壮和安全的类设计。