1

我正在阅读“Learning JS DataStructs and Algorithms”一书,并在书中说“项目”在下一堂课中是公开的。

class Stack {
    constructor(){
      this.items = []
    }
 }

但是,如果我使用 Wea​​kMap,那么我可以再次将项目设为私有,仅在给出的示例中,他们没有像我期望的那样使用“this”。

const items = new WeakMap();
class Stack {
    constructor(){
      items.set(this, []);
    }
}

然后它给出了执行 items.set 或 items.get 之类的操作来访问事物的代码示例,这看起来不错,但我想知道是否可以将构造函数中对 item.get(value) 的访问缩短到“这个”像这样:

const items = new WeakMap();
class Stack {
    constructor() {
        items.set(this, []);
        this.stack = items.get(this, []);

     push(item) {
         this.stack.push(item)
     }
}

现在,我可以使用 this.stack 访问 items.get() 功能,但我不确定它是否会再次公开,并且想知道是否有人可以帮我解决这个问题?

4

1 回答 1

1

是的 - 的任何财产this实际上都是公共的。因此,如果您有this.stack, 并且stack引用了一个数组,那么该数组将可以从任何可以访问实例化对象的东西中查看和更改,这可能是您不想要的。

请注意,即使在第二个代码片段中,使用items WeakMap也不足以使数据私有- 例如,任何可以同时访问items和实例化对象的东西都可以更改该项目的数组:

const items = new WeakMap();
class Stack {
  constructor() {
    items.set(this, []);
  }
}

const s = new Stack();
items.get(s).push('foo');
console.log(items.get(s));

为了解决这个问题,一种选择是将整个东西放在 IIFE 中,items范围IIFE 内,然后返回类:

const Stack = (() => {
  const items = new WeakMap();
  return class Stack {
    constructor() {
      items.set(this, []);
    }
  };
})();
const s = new Stack();
// now, items can only be seen and modified through Stack's internal methods

于 2018-11-19T07:07:16.310 回答