ES6功能扩展-类的私有属性和方法

私有属性和方法

在es6中,官方并没有为类规定私有属性和方法,传统的做法是使用'_'开头的公有属性和方法来表示

class Person {
  constructor(age) {
    this._age = age; // 私有属性
  }
  _sayAge() { // 私有方法
    return this._age
  }
}

上面的方式本质上是无法起到保护效果的,一种新的比较安全的方法是使用symbol的唯一性,创建私有属性和方法

const age = Symbol('age');
const sayAge = Symbol('sayAge');

export default class Person {
  constructor(ageArg) {
    this[age] = ageArg; // 私有属性
  }
  [sayAge]() { // 私有方法
    return this[age]
  }
}

// 其他文件中使用
const p = new Person(18)

这种方式在一定程度上起到了保护作用,但也不是绝对的无法访问,使用Reflect.ownKeys(Person.prototype)方法可以读取到Person的key列表,然后通过索引的方式仍然能访问到私有属性和方法。

最新的ES提案是使用#号来表示私有属性和方法

class Person {
  #age;
  constructor(age) {
    this.#age = age
  }
  #sayAge() {
    return this.#age
  }
}
posted @ 2021-09-28 18:23  wmui  阅读(390)  评论(0编辑  收藏  举报