Encapsulating in JavaScript, does it exist?

前端 未结 4 978
予麋鹿
予麋鹿 2021-01-07 00:03

I have an experience with the C# programming language, but I also have to work with the JS now and it\'s rather new for me.

I have tried to develop a simple class em

4条回答
  •  醉酒成梦
    2021-01-07 01:01

    Javascript still does not support encapsulation out of the box. However there is a proposal to make it so.

    ECMA TC39 had proposed a private syntax. According to the proposal, in order to make a javascript class field private you need to prefix it with a hash '#'. This is to provide some sort of runtime encapsulation.

    Example:

    class B {
      #hidden = 0;
      m() {
        return this.#hidden;
      }
    }
    

    Chrome supports this since Chrome v74. If this private-syntax becomes a standart we will be able to benefit from runtime encapsulation in javascript.

提交回复
热议问题