Why do js classes not use public and private keywords?

∥☆過路亽.° 提交于 2020-08-11 01:10:26

问题


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.

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;

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.


回答1:


The official FAQ answers it:

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



来源:https://stackoverflow.com/questions/55394831/why-do-js-classes-not-use-public-and-private-keywords

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!