Would a “circular” reference be treated as “reachability” for a WeakMap?

拈花ヽ惹草 提交于 2019-12-21 09:28:02

问题


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

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

  return w;
}

const weakMap = f();

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

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


回答1:


Quoting 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.

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 implementations must detect and remove such key/value pairs and any associated resources.

So, it would be eventually garbage collected.



来源:https://stackoverflow.com/questions/32687100/would-a-circular-reference-be-treated-as-reachability-for-a-weakmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!