0

It's acknowledge that we can access a property of an object by two ways :foo.bar and foo['bar'], but when I use the new feature # to declare a private member in class, it won't work properly:

class FooBar{
    constructor(){}
    testCall(name){
        this[name]()
    }
    bar(){console.log(1)}
    #bar(){console.log(2)}
}
let foo = new FooBar();
foo.testCall('bar');   //this line works properly
foo.testCall('#bar');  //Uncaught TypeError: this[name] is not a function

Can someone please tell how can I modify it to make the code work properly

AMORE
  • 99
  • 8
  • Does this answer your question? [Can I set a private class field using a variable as identifier? How?](https://stackoverflow.com/questions/58297106/can-i-set-a-private-class-field-using-a-variable-as-identifier-how) – dellink Feb 14 '22 at 08:11
  • This isn’t possible. See [Dynamic Access of Private FIelds](//github.com/tc39/proposal-private-fields/issues/104). Try to avoid dynamic private field names just like dynamic variable names. – Sebastian Simon Feb 14 '22 at 08:11
  • The idea of private/protected in languages is encapsulation (hiding implementation details from the outside so that those can be safely changed - as long as the described behavior does not change - without breaking any outside code) . So even if `foo.testCall('#bar')` would be possible, it would be a bad idea, this would contradict the ideas behind making something private/protected. – t.niese Feb 14 '22 at 08:22
  • You can always do `if(name==='#var') { this.#bar() }`. You now might wonder how that is different to `this[name]()`. The reason for that is explicitly, now you know that you expose `#bar()` through a string. This might still not be a good idea, but better than blindly exposing **all** private property. – t.niese Feb 14 '22 at 08:27

0 Answers0