Hard-private vs soft-private · Issue #33 · tc39/proposal-private-fields (original) (raw)

Should private state have an "escape hatch" like TypeScript private, or be strongly private the way that closed-over values are? Soft-private isn't fully written out the way that @zenparsing has done an excellent job on the current WeakMap-based proposal, but the core would be that "private state" is simply (public) symbol-named properties, with syntactic sugar for those symbols, and possibly some kind of introspection over them. It might be bad for overall language complexity/intelligibility to have both kinds of private state in the language and better to decide up-front what we want. Below, I @-mention people who either made this argument or who I think might be especially interested in the argument.

Soft-private

Soft-private would be syntactic sugar for symbols. In ES6, you can currently write code like this:

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

With a soft-private language feature, there would be syntactic sugar that looks like this:

Advantages

Disadvantages

Hard-private

Hard-private (the proposal described in this repository currently) is based on state that can really only be accessed by code within the class body. This has been constant across all of the different proposals that have been advanced to TC39, though not what TypeScript provides.

Advantages

let get, set; class Foo { #bar static { get = x => x.#bar; set = (x, y) => x.#bar = y; } }

Even without static blocks, you could create a static method which does the exporting, though this is ugly.

Disadvantages

Thoughts?