关于javascript:为什么无法枚举ES6 WeakMap?

Why will ES6 WeakMap's not be enumerable?

在我重新进入JavaScript(及相关)之前,我已经完成了很多ActionScript 3,并且那里有一个Dictionary对象,该对象具有弱键,就像即将发布的WeakMap一样。 但是AS3版本仍然像常规通用对象一样可枚举,而WeakMap专门没有.keys().values()

AS3版本允许我们绑定一些非常有趣且有用的结构,但我觉得JS版本有些局限。 这是为什么?

如果Flash VM可以做到,那么是什么阻止浏览器这样做呢? 我读到它将是"不确定的",但这是正确的吗?


终于找到了真正的答案:http://tc39wiki.calculist.org/es6/weak-map/

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.


这是一个权衡。 如果介绍支持枚举的对象<->对象字典,则有两种与垃圾回收有关的选项:

  • 将键条目视为一个强大的参考,可以防止垃圾回收用作键的对象。

  • 使其成为弱引用,以便每当其他所有引用都消失时,就可以对其键进行垃圾回收。

  • 如果您执行#1操作,您将很容易通过将大物体泄漏到整个内存中来用脚射击自己。 另一方面,如果使用选项#2,则密钥字典将取决于应用程序中垃圾回收的状态,这将不可避免地导致无法跟踪错误。