Private fields in sub-objects within class definition.

#!/JoePea joe at trusktr.io
Fri Aug 7 20:32:18 UTC 2020


Not sure if the following is exactly how we'd want it to be, but it
would be useful:

```js
class Foo {
  // calculatedValue is intended to have read-only properties
  calculatedValue = {
    #x: 0,
    get x() { return this.#x },
    #y: 0,
    get y() { return this.#y },
    #z: 0,
    get z() { return this.#z },
  }

  update() {
    this.calculatedValue.#x = 42 // ok
    this.calculatedValue.#y = 42 // ok
    this.calculatedValue.#z = 42 // ok
  }
}
```

End user:

```js
const foo = new Foo
foo.calculatedValue.x // ok
foo.calculatedValue.#x // syntax error
```

We could currently do something like this:

```js
class Foo {
  #calcX = 0
  #calcY = 0
  #calcZ = 0

  // calculatedValue is intended to have read-only properties
  calculatedValue = (() => {
    const self = this
    return {
      get x() { return self.#calcX },
      get y() { return self.#calcY },
      get z() { return self.#calcZ },
    }
  })()

  update() {
    this.#calcX = 42 // ok
    this.#calcY = 42 // ok
    this.#calcZ = 42 // ok
  }
}
```

Any plans for something like this? Is there a plan for private fields
for object literals? If so, maybe that can somehow tie into usage
within class bodies with WeakMap-ish semantics.

#!/JoePea


More information about the es-discuss mailing list