Is it possible to create private properties in ES6 classes?

Here's an example. How can I prevent access to instance.property?

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

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

推荐答案

Private class features is in Stage 3 proposal. The majority of its features are supported by all major browsers.

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

Javascript相关问答推荐

切换时排序对象数组,切换不起作用

我们如何从一个行动中分派行动

CheckBox作为Vue3中的一个组件

Html文件和客户端存储的相关问题,有没有可能?

Reaction Native中的范围滑块

覆盖加载器页面避免对页面上的元素进行操作

同一类的所有div';S的模式窗口

变量在导入到Vite中的另一个js文件时成为常量.

从另一个数组中的对应行/键值对更新数组中的键值对对象

如果没有页面重新加载Angular ,innerHTML属性绑定不会更新

输入的值的类型脚本array.排序()

通过跳过某些元素的对象进行映射

无法使用npm install安装react-dom、react和next

如何设置时间选取器的起始值,仅当它获得焦点时?

使用Java脚本筛选数组中最接近值最小的所有项

CSS网格使页面自动滚动

在ReactJS上挂载组件时获得多个身份验证请求

在使用Jest进行测试时,在Express应用程序中未定义Multer

ReactJS:根据AXIOS开机自检结果以红色/绿色背景显示状态

使用条件 Select 下拉菜单时更改元素的样式