[英]ES6 WeakMap Class encapsulation
I'm trying to understand why I need to use WeakMaps to create private class members, instead of just using a normal variable. 我试图理解为什么我需要使用WeakMaps创建私有类成员,而不仅仅是使用普通变量。 They both create encapsulation with closures, and module imports.
它们都使用闭包和模块导入来创建封装。
(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!
The problem with an ordinary variable like my_var
is that it will only save data for a single instantiation of the class: 像
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'
Thus, the need for a WeakMap
, to hold separate data for each instantiation : 因此,需要一个
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.