JavaScript ES6 クラスのプライベートプロパティ 質問する

JavaScript ES6 クラスのプライベートプロパティ 質問する

ES6 クラスでプライベート プロパティを作成することは可能ですか?

ここに例があります。 へのアクセスを防ぐにはどうすればよいですかinstance.property?

class Something {
  constructor(){
    this.property = "test";
  }
}

var instance = new Something();
console.log(instance.property); //=> "test"

ベストアンサー1

プライベートクラスの機能現在、ほとんどのブラウザでサポートされています。

class Something {
  #property;

  constructor(){
    this.#property = "test";
  }

  #privateMethod() {
    return 'hello world';
  }

  getPrivateMessage() {
      return this.#property;
  }
}

const instance = new Something();
console.log(instance.property); //=> undefined
console.log(instance.privateMethod); //=> undefined
console.log(instance.getPrivateMessage()); //=> test
console.log(instance.#property); //=> Syntax error

おすすめ記事