为什么js类不使用public和private关键字? [英] Why do js classes not use public and private keywords?

查看:475
本文介绍了为什么js类不使用public和private关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,当他们创建es6类时,默认情况下它们只是将所有内容公开,这对我来说有点奇怪,但是鉴于我仍然使用较旧的基于es5样式范围的类,我就选择了它。

So when they created es6 classes they just made everything public by default, and that was a bit odd to me but I just went with it, given I still used the older es5 style scope based classes.

无论如何,现在几年后我们都在课堂上招募私人成员,这看起来很棒,但是接下来您要看看synax:

Anyway a few years on now we are getting private members in classes, which seems great, but then you look at the synax:

somePublicVar = 10;
#somePrivateVar = 20;

如您所见,我们现在必须在私有内容前加上井号/井号,这似乎是鉴于JS具有 public private 关键字,这些关键字保留供将来使用,因此这很奇怪,所以现在我们要区分

As you can see we now have to prefix the private stuff with the hash/pound sign which seems a very odd choice given JS has public and private keywords which are reserved for future use, so now we want to differentiate between public and private why not just now do.

public somePublicVar = 10;
private somePrivateVar = 20;

所以我敢肯定有一个技术上的原因,但是我正在努力寻找它,因为那样会现在似乎是将那些公开私有从保留更改为使用中的绝佳时机,

So I am sure there is a technical reason why but I am struggling to find it, as it would seem now would be the perfect time to turn those public and private from reserved to "in use", making it a bit more explicit and obvious as to the access modifiers of a given member.

推荐答案

官方常见问题解答回答:


为什么声明不是 private x



这种声明是什么其他语言使用(特别是Java)
表示使用 this.x 进行访问。假设
不是这种情况(请参见上文),那么在JavaScript中,这会默默地创建
或访问公共字段,而不是抛出错误。这是
的主要潜在错误来源,也可能是
打算公开使用的不公开字段。

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;
  }
}

https://github.com/tc39/proposal- class-fields / blob / master / PRIVATE_SYNTAX_FAQ.md#why-arent-declarations-private-x

这篇关于为什么js类不使用public和private关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆