Skip to content Skip to sidebar Skip to footer

How To Get Access To Private Field Via Square Brackets In Javascript

This code works: class Test { #field get field() { return this.#field; } } But if I want to calculate field name I have to use square brackets but it doesn't work: clas

Solution 1:

It looks like it is a problem to hand over a string which has a special meaning.

If really necessary, you evaluate a string.

classTest {
    #field = 'foo';

    getfield() {
        returneval('this.' +'#field');
    }
}

console.log(newTest().field)

Solution 2:

This is not possible. From the proposal:

There are no private computed property names: #foo is a private identifier, and #[foo] is a syntax error.

and its FAQ:

Why doesn't this['#x'] access the private field named #x, given that this.#x does?

  1. This would complicate property access semantics.

  2. Dynamic access to private fields is contrary to the notion of 'private'. E.g. this is concerning:

classDictextendsnull {
  #data = something_secret;
  add(key, value) {
    this[key] = value;
  }
  get(key) {
    returnthis[key];
  }
}

(newDict).get('#data'); // returns something_secret

But doesn't giving this.#x and this['#x'] different semantics break an invariant of current syntax?

Not exactly, but it is a concern. this.#x has never previously been legal syntax, so from one point of view there can be no invariant regarding it.

On the other hand, it might be surprising that they differ, and this is a downside of the current proposal.

See also this issue.

Post a Comment for "How To Get Access To Private Field Via Square Brackets In Javascript"