无法理解ECMA6中WeakMap的行为

Not able to understand the behavior of WeakMap in ECMA6

本文关键字:WeakMap ECMA6      更新时间:2023-09-26

我在ECMA6中玩WeakMap时遇到了一个奇怪的场景。我正在写一门课,内容如下

'use strict';
class WeekMaptest {
    constructor(options){
        console.log("constructor");
        this.weekMap = new WeakMap();
        this._init(options);
    }
    _init(options) {
        console.log("init called");
        var privateProps = {
            name: options.name,
            email: options.email
        };
        this.weekMap.set(this, privateProps);
    }
    getName(){
        return this.weekMap.get(this).name;
    }

}

现在调用这个类来实例化一个对象

var obj = new WeekMaptest({name: 'Rohit', email: 'rohit.choudhar@gmail.com'});

输出来了

console.log(obj.getName());
Output : Rohit
console.log(obj.weekMap.get(obj).name);
Output : Rohit
console.log(obj.weekMap.set(obj).name = 'I mena');
Output : I mena
console.log(obj.weekMap);
Output: WeakMap { name: 'I mena' }
console.log(obj.weekMap.get(obj).name);
Error:
/home/bll/bll-jb/server/lib/ease/testweak.js:35
console.log(obj.weekMap.get(obj).name);
                                ^
TypeError: Cannot read property 'name' of undefined
    at Object.<anonymous> (/home/bll/bll-jb/server/lib/ease/testweak.js:35:33)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:475:10)
    at startup (node.js:117:18)
    at node.js:951:3

我无法弄清楚WeakMap的这种行为。

我猜您混淆了setget

console.log(obj.weekMap.set(obj).name = 'I mena');

此调用之前的条目:obj=>obj

此调用后的条目:obj=>未定义的

set需要键和值的参数。您没有提供值,因此此代码将键为obj的条目的值设置为undefined。因此,对obj.weekMap.get(obj)的下一个调用返回undefined。