1 of 8

Private State

Daniel Ehrenberg (littledan)

2 of 8

Syntax

class Foo {

#x;

#y = z;

foo() { #x++; return this.#x }

}

3 of 8

Semantics

  • Only accessible from methods inside class body (“hard-private”)
  • Internal slots mapping objects to field values
  • Add field after super() returns, or at beginning in base class
  • Intersperse initializer evaluation with field addition
  • Throw on redundant property definition
  • Scope of initializers as in property declarations

4 of 8

Interaction with other features

  • Decorators -- reify a PrivateFieldIdentifier() object (explainer)
    • A decorator can provide soft-private state
  • Private methods -- a clean extension with the syntax you expect (explainer)
  • Static private -- ditto (explainer)
  • Friends -- may be lexically exposed via static block

let barGetter;�class Foo {� #bar;� static { barGetter = instance => instance.#bar }�}

5 of 8

Why inaccessible private state? (bug)

  • More guarantees for high-fidelity library/polyfill authors
    • Platform objects with internal slots do not have an “escape hatch” within ES
  • Stronger invariants--precise control of friends
  • Implementations and and security frameworks see uses (without eval)
  • “Soft-private” already available through explicit symbol use

let x = Symbol("x");�class Foo {� [x] = 1;�}

  • or TypeScript-style tool-based checking

6 of 8

Internal slot-based specification mechanics

  • We have gone back and forth here… Now:
  • Private State Identifier specification type
  • [[PrivateStateValues]] is a List with pairs mapping Private State Identifiers to their values
  • Difference from WeakMaps unobservable except for implied GC semantics

7 of 8

Open questions

  • Should private state be accessible within eval?
  • Is this proposal too unergonomic to be workable?
  • Should static private, methods be included in this proposal?
  • Should we put private before the declaration?
  • General field issues: = token, scope for initializer

8 of 8

Current status

  • New internal slot spec mechanics
  • New explainers for interactions with other features
  • Still missing some spec text for more early errors
  • Stage 2?