Implementing private instance variables in Javascript

后端 未结 4 1001
夕颜
夕颜 2020-12-05 03:07

I don\'t know how I\'ve missed this for so long. I\'ve been presuming private instance variables to work like this, but they don\'t. They\'re private (as in non-global), cer

4条回答
  •  温柔的废话
    2020-12-05 03:38

    If you are willing to use ES2015 classes (I already answered it here, but repeating for the sake of convenience),

    with ESNext, you can use Javascript private variables like this:

    class Foo {
      #bar = '';
      constructor(val){
          this.#bar = val;
      }
      otherFn(){
          console.log(this.#bar);
      }
    }
    

    Private field #bar is not accessible outside Foo class.

提交回复
热议问题