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/