JavaScript 类属性私有化
1、使用 Symbol 类
const _items = Symbol("item");
class Test {
constructor() {
this[_items] = [1,2];
this.count = 1;
}
}
使用该类虽然无法直接通过 Test._items 获取到值,但它可以被 Object.getOwnPropertySymbols 方法获取到。
但没关系,还有第二种方法。
2、使用 WeakMap 类
const items = new WeakMap();
class Test {
constructor() {
items.set(this,[]);
this.count = 1;
}
}
使用这个类的话,同样无法通过 Test.items 获取到值。
并且在该类里面,也只能通过 items.get(this) 来获取值。
不过值得注意的是,在扩展该类时,无法继承其私有属性!
3、在类里为属性添加 # 号
class Test {
#count = 1;
#items = [];
}
通过这个方式,同样无法通过 Test["#items"] 来获取该类里的 #items 的值,但实际上打印 Test 的这个类的时候又能够看到它。