我正在阅读“Learning JS DataStructs and Algorithms”一书,并在书中说“项目”在下一堂课中是公开的。
class Stack {
constructor(){
this.items = []
}
}
但是,如果我使用 WeakMap,那么我可以再次将项目设为私有,仅在给出的示例中,他们没有像我期望的那样使用“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() 功能,但我不确定它是否会再次公开,并且想知道是否有人可以帮我解决这个问题?