javascript真●私有變量

想必你們已經見過私有變量的各類花式寫法。
如下是真●私有變量標準寫法。javascript

標準寫法

class Foo {
    pub = "pub";
    #pri = "pri";
    get Pri () {
        return this.#pri;
    }
    set Pri (v) {
        this.#pri = v;
    }
}
const f = new Foo;
f.pub      \\ pub
f.#pri     \\ Uncaught SyntaxError: Undefined private field #pri: must be declared in an enclosing class
f.Pri      \\ Pri 
f.Pri = "real pri"
f.Pri      \\ real pri

兼容狀況

  1. 瀏覽器上,只有chrome直接支持(下筆時chrome的最新版本爲74)。
  2. 隨着 nodejs 12 的發佈,服務端已經能夠直接使用這個語法。
相關文章
相關標籤/搜索