Understanding “public” / “private” in typescript class

前端 未结 3 881
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 15:22

In the below type script code , irrespective of whether name is \"public\" or \"private\" , java script code that is generated is same.

So my question is, how to decide

3条回答
  •  鱼传尺愫
    2021-02-05 15:29

    In ESnext, private class fields are defined using a hash # prefix:

    class MyClass {
      a = 1;          // .a is public
      #b = 2;         // .#b is private
      static #c = 3;  // .#c is private and static
      incB() {
        this.#b++;
      }
    }
    
    const m = new MyClass();
    m.incB(); // runs OK
    m.#b = 0; // error - private property cannot be modified outside class
    

    *Note: there’s no way to define private methods, getters and setters.

    but a proposal is there https://github.com/tc39/proposal-private-methods

提交回复
热议问题