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

Enumeration of Private Fields #278

Closed anthumchris closed 5 years ago

anthumchris commented 5 years ago

Could we make private fields accessible for enumeration within an instance? Currently, only public fields are reflected. Given that we can explicitly access private fields within an instance, it would also be useful to enumerate on them too:

class Person {
  #isFoo = true;

  constructor(first) {
    this.fullName = first;
  }

  enumerateSelf() {
    console.log(this); // (public/priv fields displayed)

    // enumerate through instance fields
    for (let key in this) {
      console.log(key) // (only public fields shown)
    }
  }
}

new Person('J Doe').enumerateSelf()
bergus commented 5 years ago

Relevant: https://github.com/tc39/proposal-private-fields/issues/94

Btw, what would you expect key to be in that loop, and how would you want to use it?

anthumchris commented 5 years ago

Thanks @bergus! Yes, this looks like a duplicate and I'll close. And you make a great point: key could not be used to access even if it were avail.

trusktr commented 4 years ago

key could not be used to access even if it were avail.

That is one thing that makes this proposal confusing. Is #foo a key name? Or not? If it isn't, then is .# an operator? 🤔

ljharb commented 4 years ago

It is a name, but not of a property key, and unlike a property key (which can be reified as a string or a symbol) a private name has no first-class representation. This proposal adds no new operators.

trusktr commented 4 years ago

Oh ok, good to know. ;)

trusktr commented 4 years ago