Private fields in sub-objects within class definition.

# #!/JoePea (4 years ago)

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

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:

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

We could currently do something like this:

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

# Michael Theriot (4 years ago)

Why stop at class definitions?

e.g.

let obj;
{
  let local = 0;
  obj = {
    get local() {
      return local;
    }
  }
}

becomes

const obj = {
  #local: 0,
  get local() {
    return this.#local;
  }
}
# #!/JoePea (4 years ago)

Sure, but I'm first curious about classes because in my example, the code is all defined inside a class definition's lexical scope, where private fields (or keys) are currently defined to exist, so it seems like an approach we can currently take.

Private fields on objects without classes being in play would be neat too!

#!/JoePea