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
// 私有余额的公共getter
14 getBalance() {
15 return this.#balance;
16 }
17}
18
// 创建账户并链接操作
19const account = new BankAccount();
20account.deposit(100).deposit(50).withdraw(30);
// 通过公共方法获取余额: 120
21console.log(account.getBalance());

运行结果

120
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 JavaScript 代码中需要输入的符号及其出现次数。

  • (× 11
  • )× 11
  • ;× 9
  • .× 9
  • #× 5
  • =× 5
  • {× 4
  • }× 4
  • &× 2
  • >× 2

JavaScript 等级 5 的更多代码示例

← 返回 JavaScript 打字练习