1

「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() 機能にアクセスできますが、それが再び公開されるかどうかはわかりません。

4

1 に答える 1