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?

1
  • You could try: this[eval(VarNamePrefixed)] Commented Oct 9, 2020 at 10:37

2 Answers 2

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'.
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Hm, That works I Suppose. Not a great solution but if there is no alternative...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.