lundi 16 décembre 2019

How to access private properties in javascript

Now that private properties have landed in chrome, I played around with them and wanted to figure out how to reflect/inspect those properties. Reading the proposal I can't seem to find a way to access them as they are in stored in virtual WeakSets.

Eg.


{
    const privProp = Symbol('private');
    class Test {
      _pripProp = 123; // old style 'private'
      [privProp] = 123; // symbol style private
      #test = 456; // true private
    }

  const t = new Test();
  console.log(Object.getOwnPropertyDescriptors(t));
}

Yields:

{
  _privProp: {value: 123, writable: true, enumerable: true, configurable: true}
  Symbol(private): {value: 123, writable: true, enumerable: true, configurable: true}
  // No reference to `test`
  __proto__: Object

HOWEVER, the chrome debugger/console.log seems to have reflection capabilities.

Eg.

  const t = new Test();
  console.log(t);

Yields:

_privProp: 123
#test: 456
Symbol(private): 123
__proto__: Object

I'm assuming it's using some built-in v8 functions to access those though.

Can someone shed some light on this?





Aucun commentaire:

Enregistrer un commentaire