tc39 / proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
https://arai-a.github.io/ecma262-compare/?pr=1668
1.72k stars 113 forks source link

Returning Private Fields in Object #238

Closed pnewell closed 5 years ago

pnewell commented 5 years ago

I am having some trouble testing out private fields with web components.

Switch this:

class MyApp extends connect(store)(LitElement) {
  static get properties() {
    return {
      appTitle: { type: String },
      _page: { type: String },
      _snackbarOpened: { type: Boolean },
      _offline: { type: Boolean }
    };
  }

To this:

class MyApp extends connect(store)(LitElement) {
  static get properties() {
    return {
      appTitle: { type: String },
      #page: { type: String },
      #snackbarOpened: { type: Boolean },
      #offline: { type: Boolean }
    };
  }

Gives errors in both babel and Chrome 74.

Babel: Unknown PrivateName "#page"

Chrome: Uncaught SyntaxError: Unexpected identifier

ljharb commented 5 years ago

Private fields apply to class instances - not to object literals. In other words, MyApp, or instances of MyApp, but not the object you're returning in that static method.

pnewell commented 5 years ago

Is there a way around this? Or is it just not possible to use this new functionality with web components and/or lit-element?

ljharb commented 5 years ago

I'm not familiar with lit-element, but web components can certainly have their own private properties - but a .properties accessor surely would only reveal public properties, not private ones?

jhpratt commented 5 years ago

LitElement uses this info to determine what properties to observe changes on. If you could return private fields, that would violate the hard private requirement.

littledan commented 5 years ago

There's a scoping issue with private fields in objects: it is unclear whether this would be declaring a new private name or using the outer declared private name. @jridgewell is working on explicit syntax here which could help with the basis for private fields in object literals in a follow-up proposal

littledan commented 5 years ago

I can see how this feature would be useful, but it faces technical difficulties described in https://github.com/tc39/proposal-class-fields/issues/238#issuecomment-492176443 . For this reason, it's left to be developed in a future proposal.