1

Why is private field in JavaScript not accessible using bracket ([]) notation but accessible using dot (.) notation?

  • Using dot notation:

        class MyClass {
          #privateField = 42;
    
          publicMethod() {
            console.log(this.#privateField);
          }
        }
    
        const obj = new MyClass();
        obj.publicMethod(); // 42

  • Using bracket notation:

        class MyClass {
          #privateField = 42;
    
          publicMethod() {
            console.log(this['#privateField']);
          }
        }
    
        const obj = new MyClass();
        obj.publicMethod(); // undefined

2
  • What would you need this for? Commented May 19 at 17:40
  • 3
    Private fields are private for a reason. Commented May 19 at 18:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.