Private fields can not be accessed dynamically.
One way to get dynamic private fields is with Symbols.
A symbol is a scalar, just like a string.
You create symbols like this:
let myXyzSymbol = Symbol('my_xyz_symbol');
// note the absence of `new`
A symbol is always unique. This means that following is always false
:
Symbol('x') === Symbol('x')
Now, we have all the pieces to do something about dynamic privates.
Create a symbol and do not export it outside the module. This makes it private.
const mySym = Symbol('foo');
export class Something {
[mySym]() {
// This function can not be called by
// a caller that does not have access to mySym.
}
}
More on Symbols
- The
Symbol.for()
function is different from Symbol()
, but both return a symbol.
- Check out the MDN docs for Symbols
- And an article here