问题
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