2

Lets say you have a class like this:


class ExampleClass {

    #foo;
    constructor(){

        let VarName = 'foo';
        let VarNamePrefixed = '#foo';

        this[#VarName] = 'Bar'; // won't work, syntax error.
        this[VarNamePrefixed] = 'Bar'; // Won't work, escapes into a string.

    }

}

Is there a nice way to set private (#foo) variables using the array notation?

BeepSterr
  • 83
  • 10

2 Answers2

1

You cannot use [] syntax to access private fields.

See the private syntax FAQ.

  1. This would complicate property access semantics.
  2. Dynamic access to private fields is contrary to the notion of 'private'.
Matt Ellen
  • 11,268
  • 4
  • 68
  • 90
0

I don't think you can use square brackets for this, the closest I can think of is using eval, which wouldn't be wise (in any case I don't really see the point, as you'll need to define the private property outside the constructor and not even eval will work there).

class ExampleClass {

  #foo
  constructor(){
    let VarNamePrefixed = '#foo'

    eval("this." + VarNamePrefixed + ' = "Bar"')

    console.log(this.#foo)
  }
}

var foo = new ExampleClass
alotropico
  • 1,904
  • 3
  • 16
  • 24