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.
添加回答
举报