javascript – 为什么不推荐使用WeakMap clear()方法?

前端之家收集整理的这篇文章主要介绍了javascript – 为什么不推荐使用WeakMap clear()方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我一直在用 JavaScript工作 WeakMaps,在检查文档后我意识到明确的方法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过程.因此,为了确保可预测的设计,也清除了清晰.

原文链接:https://www.f2er.com/js/150231.html

猜你在找的JavaScript相关文章