为什么js 类不用public和私有关键字?
Why do js classes not use public and private keywords?
因此,当他们创建 es6 类 时,他们只是将所有内容都默认设置为 public,这对我来说有点奇怪,但我还是接受了,因为我仍然使用旧的 es5 样式基于范围 类.
不管怎么说,几年后我们在 类 中获得了私有成员,这看起来很棒,但是你看看 synax:
somePublicVar = 10;
#somePrivateVar = 20;
如你所见,我们现在必须在私有内容前加上 hash/pound 符号,这似乎是一个非常奇怪的选择,因为 JS 有 public
和 private
关键字保留给将来使用,所以现在我们要区分 public 和私有为什么不现在就做。
public somePublicVar = 10;
private somePrivateVar = 20;
所以我确信有一个技术原因,但我正在努力寻找它,因为现在看来是将 public
和 private
从保留转为保留的最佳时机"in use",使给定成员的访问修饰符更加明确和明显。
官方FAQ回答:
Why aren't declarations private x
?
This sort of declaration is what other languages use (notably Java),
and implies that access would be done with this.x
. Assuming that
isn't the case (see above), in JavaScript this would silently create
or access a public field, rather than throwing an error. This is a
major potential source of bugs or invisibly making public fields which
were intended to be private.
It also allows a symmetry between declaration and access, just as
there is for public fields:
class A {
pub = 0;
#priv = 1;
m() {
return this.pub + this.#priv;
}
}
因此,当他们创建 es6 类 时,他们只是将所有内容都默认设置为 public,这对我来说有点奇怪,但我还是接受了,因为我仍然使用旧的 es5 样式基于范围 类.
不管怎么说,几年后我们在 类 中获得了私有成员,这看起来很棒,但是你看看 synax:
somePublicVar = 10;
#somePrivateVar = 20;
如你所见,我们现在必须在私有内容前加上 hash/pound 符号,这似乎是一个非常奇怪的选择,因为 JS 有 public
和 private
关键字保留给将来使用,所以现在我们要区分 public 和私有为什么不现在就做。
public somePublicVar = 10;
private somePrivateVar = 20;
所以我确信有一个技术原因,但我正在努力寻找它,因为现在看来是将 public
和 private
从保留转为保留的最佳时机"in use",使给定成员的访问修饰符更加明确和明显。
官方FAQ回答:
Why aren't declarations
private x
?This sort of declaration is what other languages use (notably Java), and implies that access would be done with
this.x
. Assuming that isn't the case (see above), in JavaScript this would silently create or access a public field, rather than throwing an error. This is a major potential source of bugs or invisibly making public fields which were intended to be private.It also allows a symmetry between declaration and access, just as there is for public fields:
class A { pub = 0; #priv = 1; m() { return this.pub + this.#priv; } }