JavaScript 的 私有类字段
等级 5371 次按键
使用私有类字段(#)封装余额,只能通过方法访问。
JavaScript 代码
// 定义具有封装的类1class BankAccount { // #前缀使字段真正私有 // 无法从类外部访问2 #balance = 0;3 // 添加金钱的公共方法4 deposit(amount) { // 只接受正数金额5 if (amount > 0) this.#balance += amount;6 }7 // 取款的公共方法8 withdraw(amount) { // 验证: 正数金额且余额充足9 if (amount > 0 && amount <= this.#balance) {10 this.#balance -= amount;11 return amount;12 } // 取款失败返回013 return 0;14 }15 // 安全访问余额的getter方法16 getBalance() {17 return this.#balance;18 }19}20 // 创建账户实例21const account = new BankAccount();// 存入10022account.deposit(100);// 取出3023account.withdraw(30);// 输出: 7024console.log(account.getBalance());运行结果
70
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 JavaScript 代码中需要输入的符号及其出现次数。
;× 10(× 10)× 10.× 8{× 5}× 5#× 5=× 5&× 2>× 2