JavaScript 的 私有类字段
等级 5371 次按键
私有类字段(带#)提供真正的封装,只能在类内访问。
JavaScript 代码
// 使用#语法的私有字段的类1class BankAccount { // 私有字段 - 不能在类外访问2 #balance = 0;3 // deposit方法 - 验证并更新余额4 deposit(amount) {5 if (amount > 0) this.#balance += amount; // 返回this用于方法链6 return this;7 }8 // withdraw方法 - 检查足够的资金9 withdraw(amount) {10 if (amount > 0 && amount <= this.#balance) this.#balance -= amount;11 return this;12 }13 // 私有余额的公共getter14 getBalance() {15 return this.#balance;16 }17}18 // 创建账户并链接操作19const account = new BankAccount();20account.deposit(100).deposit(50).withdraw(30);// 通过公共方法获取余额: 12021console.log(account.getBalance());运行结果
120
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 JavaScript 代码中需要输入的符号及其出现次数。
(× 11)× 11;× 9.× 9#× 5=× 5{× 4}× 4&× 2>× 2