ES6 WeakMap类封装 [英] ES6 WeakMap Class encapsulation

查看:54
本文介绍了ES6 WeakMap类封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解为什么我需要使用WeakMaps创建私有类成员,而不仅仅是使用普通变量.它们都使用闭包创建封装,并导入模块.

I'm trying to understand why I need to use WeakMaps to create private class members, instead of just using a normal variable. 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!

推荐答案

my_var这样的普通变量的问题在于它只会保存该类的单个实例的数据:

The problem with an ordinary variable like my_var is that it will only save data for a single instantiation of the class:

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来保存每个每个实例的单独数据:

Thus, the need for a WeakMap, to hold separate data for each instantiation:

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

这篇关于ES6 WeakMap类封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆