为什么不推荐使用 Wea​​kMap clear() 方法?

Why is WeakMap clear() method deprecated?

我一直在与 WeakMaps in JavaScript, and after checking the documentation I realized that the clear method has been deprecated / removed from ECMAScript 6 合作。

这是什么原因? 为什么要强迫我们做一个明确的功能,如:

clear() {
  this._weakmap = new WeakMap()
}

“The mapping from weakmap/key pair value can only be observed or affected by someone who has both the weakmap and the key. With clear(), someone with only the WeakMap would’ve been able to affect the WeakMap-and-key-to-value mapping.”

Mark Miller

此限制的原因是出于安全考虑:

A key property of Weak Maps is the inability to enumerate their keys. This is necessary to prevent attackers observing the internal behavior of other systems in the environment which share weakly-mapped objects. Should the number or names of items in the collection be discoverable from the API, even if the values aren't, WeakMap instances might create a side channel where one was previously not available.

tc39wiki

可枚举的 WeakMap 也可能影响 GC,因为您可以间接观察 GC 过程。因此,为了确保可预测的设计 clear 也被删除。

它已被弃用,因为它阻止了 WeakMap 的反向实现。

Removal of WeakMap/WeakSet clear

If WeakMaps/WeakSets are not inspectable (via iteration) and do not have a clear operation, then the inverted implementation technique can be use used. This technique eliminates significant GS complexity.

反向实现描述,来自同一来源:

design for an inverted implementation:

Every object internally maintains a table (probably a hash table if it contains more than a few elements) that is used to implement WeakMap/Set. Entry in the table is a key/value pair where the key is a WeakMap/Set instance. Values are arbitrary ES values. Let's call such a table an "inverted map" and generically refer to such WeakMaps/Sets as WCs.