ES6 WeakMap类封装

时间:2018-05-28 11:24:32

标签: javascript class ecmascript-6

我试图理解为什么我需要使用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!

1 个答案:

答案 0 :(得分:3)

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