是否是“循环”的参考被视为“可达性”。对于弱地图? [英] Would a "circular" reference be treated as "reachability" for a WeakMap?

查看:91
本文介绍了是否是“循环”的参考被视为“可达性”。对于弱地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function f() {
  const w = new WeakMap();
  const o = {};

  w.set(o, { v: o });

  return w;
}

const weakMap = f();

对于给定的代码,唯一的 weakMap 项目被视为可达?因此,它是否会被垃圾收集?

For the given code, would the only weakMap item considered as reachable or not? Hence, will it be garbage collected or not?

PS:这个问题是从规范的角度提出的,而不是特定的实现。

PS: This question is asked from the perspective of the specification, not particular implementations.

推荐答案

引用 WeakMap 对象部分

Quoting WeakMap Objects section,


如果一个对象被用作WeakMap键/值对的键只能通过跟随在该WeakMap内开始的一系列引用来访问,然后该键/值对不可访问并自动从WeakMap中删除。

If an object that is being used as the key of a WeakMap key/value pair is only reachable by following a chain of references that start within that WeakMap, then that key/value pair is inaccessible and is automatically removed from the WeakMap.

在你的情况下,达到 o 的唯一方法是从<$ c中的一个键开始$ c> weakMap ,因为没有外部引用它。因此,它将被视为无法访问。

In your case, the only way to reach o would be to start from one of the keys in the weakMap, as there is no external references to it. So, it would be considered as inaccessible.


WeakMap实现必须检测并删除此类键/值对以及任何相关资源。

WeakMap implementations must detect and remove such key/value pairs and any associated resources.

因此,它最终会被垃圾收集。

So, it would be eventually garbage collected.

这篇关于是否是“循环”的参考被视为“可达性”。对于弱地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆