我试图理解为什么我需要使用 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!
普通变量的问题,例如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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)