How to get access to private field via square brackets in JavaScript

847 views Asked by At

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:

class Test {
  #field;

  get field() {
    return this['#field'];
  }
}

Is there any way to get private field with calculated name?

2

There are 2 answers

0
Nina Scholz On

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

If really necessary, you evaluate a string.

class Test {
    #field = 'foo';

    get field() {
        return eval('this.' +'#field');
    }
}

console.log(new Test().field)

0
Bergi On

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:

class Dict extends null {
  #data = something_secret;
  add(key, value) {
    this[key] = value;
  }
  get(key) {
    return this[key];
  }
}

(new Dict).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.