1 回答

TA貢獻1804條經驗 獲得超8個贊
一個可能的用途是驗證。想象一下以這種方式實現的類:Account
class Account {
#username;
#password;
constructor(name) {
this.#username = name;
}
get username() {
return this.#username;
}
set password(password) {
if (password.length < 10) {
throw "Password must be at least 10 characters long!";
}
this.#password = password;
}
get password() {
throw "Forgotten passwords cannot be retrieved! Please make a new one instead.";
}
}
我可以創建一個新帳戶,如下所示:
const myAccount = new Account('John Doe');
如果我嘗試將密碼設置為不可接受的短長度,我將收到一個錯誤:
myAccount.password = 'hunter2'; // Password must be at least 10 characters long!
如果我在忘記密碼后嘗試找回密碼,我會再次收到錯誤:
console.log(myAccount.password); // Forgotten passwords cannot be retrieved! Please make a new one instead.
添加回答
舉報