为什么显示整个集合时,为什么在弱图键和值中不会删除,但是当您显示一个元素时会删除呢?
示例具有“ nulling”值。 为什么该元素仍然存在于弱图集合中
let weakMap = new WeakMap();
let obj = {name: 'Ivan'};
//adding some new element
weakMap.set({}, obj);
obj = null;
console.log(weakMap);
console.log(weakMap.get({}));
?
在这种情况下, noreferrer“>
一个元素
示例具有“ nulling”键:
这里发生了什么?它来自什么?垃圾收集器没有时间清理所有内容,还是什么?
Example with "nulling" value. Why does the element still exist in the WeakMap collection in this case?
let weakMap = new WeakMap();
let obj = {name: 'Ivan'};
//adding some new element
weakMap.set({}, obj);
obj = null;
console.log(weakMap);
console.log(weakMap.get({}));
Whole collection
One element
Example with "nulling" key:
What's going on here? What does it come from? The garbage collector does not have time to clean up everything or what?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,
neakmap.set({},obj);
andneakmap.get({});
永远不会指其次,是 键 在弱图中弱引用,而不是值,因此将值设置为
null
弱图。取而代之的是,您需要“ null”键 2 (您需要存储的引用)。1 使用无法实现的对象作为key Will 从垃圾收集的弱图中消失,但不是因为您设置
obj = null
,而是因为仅参考该对象存在于弱图中。2 没有很好的方法来演示第二代摘要的行为尽管如此,在控制台 Will 中调试 都揭示了这种行为,尽管考虑到不同的浏览器处理控制台中的对象,即Chrome的活物。
First of all
weakMap.set({}, obj);
andweakMap.get({});
will never refer to the same element in the WeakMap because they are separate, anonymous object literals. In order for the WeakMap to be useful you need to store a reference to the object to be used as key1.Secondly, it is the key that is weakly referenced in the WeakMap, not the value, so setting the value to
null
will have no effect on the WeakMap. Instead you need to 'null' the key2 (another reason you need a stored reference to it).1 Your example using an unreachable object as key will disappear from the WeakMap on garbage collection, but not because you set
obj=null
but because the only reference to the object exists in the WeakMap.2 There is no good way to demonstrate the behaviour of the second snippet because, per the documentation, '... a WeakMap doesn't allow observing the liveness of its keys, its keys are not enumerable.' Nonetheless, debugging in the console will reveal the behaviour, though awkwardly given the variety of ways different browsers treat objects in the console, ie. chrome's live objects.