JavaScript私有类字段

Before the introduction of private class fields, we could not really enforce private properties on a class. We used conventions instead, maybe using _ as an hint that the field is private, like this:

在引入私有类字段之前,我们不能真正在类上强制私有属性。 我们改用约定,也许用_表示字段是私有的,例如:

class Counter {
  _count = 0

  increment() {
    this._count++
  }
}

But we could access the count using

但是我们可以使用

const counter = new Counter()
counter._count

We can now use private class fields that enforce private fields:

现在,我们可以使用强制执行私有字段的私有类字段:

class Counter {
  #count = 0

  increment() {
    this.#count++
  }
}

We now can’t access this value from the outside. Trying to access it will raise a syntax error.

现在,我们无法从外部访问此值。 尝试访问它会引发语法错误。

This is part of the new class fields proposal, which you can use since Chrome 72 and Node 12.

这是新类字段提案的一部分 ,您可以在Chrome 72和Node 12之后使用该提案

翻译自: https://flaviocopes.com/javascript-private-class-fields/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值