我试图理解为什么我需要使用WeakMaps来创建私有类成员,而不是仅仅使用一个普通变量。它们都使用闭包和模块导入来创建封装。
(function encapsulation() {
const my_var = 'My secret info';
const my_var2 = new WeakMap();
class Test {
constructor() {
my_var2.set(this, 'My secret info 2');
console.log(my_var); // My secret info
console.log(my_var2.get(this)); // My secret info 2
}
}
const t = new Test();
})();
console.log(my_var); // undefined
console.log(my_var2); // undefined
// Same result!发布于 2018-05-28 11:28:49
像my_var这样的普通变量的问题是,它只为类的单个实例化保存数据:
const Test = (function encapsulation() {
let my_var = 'My secret info';
class Test {
constructor(param) {
my_var = param;
}
getInfo() {
return my_var;
}
}
return Test;
})();
const t1 = new Test('foo');
const t2 = new Test('bar');
console.log(t1.getInfo());
// the above returns 'bar'... uh oh, but we passed in 'foo' to `t1`! Our data is lost!
console.log(t2.getInfo()); // 'bar'
因此,WeakMap需要为每个实例化保存单独的数据。
const Test = (function encapsulation() {
const my_var2 = new WeakMap();
class Test {
constructor(param) {
my_var2.set(this, param);
}
getInfo() {
return my_var2.get(this);
}
}
return Test;
})();
const t1 = new Test('foo');
const t2 = new Test('bar');
console.log(t1.getInfo()); // 'foo', as expected
console.log(t2.getInfo()); // 'bar', as expected
https://stackoverflow.com/questions/50565295
复制相似问题