gpt4 book ai didi

javascript - 对于 WeakMap, "circular"引用会被视为 "reachability"吗?

转载 作者:数据小太阳 更新时间:2023-10-29 04:08:55 26 4
gpt4 key购买 nike

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

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

return w;
}

const weakMap = f();

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

PS:这个问题是从规范的 Angular 问的,不是具体的实现。

最佳答案

引用 WeakMap Objects section ,

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 的唯一方法是从 weakMap 中的一个键开始,因为没有对其的外部引用。因此,它将被视为不可访问。

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

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

关于javascript - 对于 WeakMap, "circular"引用会被视为 "reachability"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32687100/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com