什么是 ECMAScript 6 WeakMap?
阅读此描述后: http://wiki.ecmascript.org/doku.php? id=harmony:weak_maps
我正在尝试掌握它,但我不了解整体情况。这是怎么回事? Firefox 6 似乎支持: http://kangax.github.com /es5-compat-table/非标准/
After reading this description: http://wiki.ecmascript.org/doku.php?id=harmony:weak_maps
I'm trying to get a hang of it, but I do not get the overall picture. What is it all about? It seems to be supported in Firefox 6: http://kangax.github.com/es5-compat-table/non-standard/
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
弱引用是包含对象指针的特殊对象,但不会使该对象保持活动状态。
弱引用的一个应用是在弱映射中实现的:
“经验丰富的 JavaScript 程序员会注意到,这个 API 可以在 JavaScript 中实现,并由 4 个 API 共享两个数组(一个用于键,一个用于值)方法。这种实施方式有两个主要的不便。第一个是 O(n) 搜索(n 是映射中键的数量)。第二个是内存泄漏问题。使用手动编写的映射,键数组将保留对关键对象的引用,从而防止它们被垃圾收集。在本机 WeakMap 中,对关键对象的引用被“弱”保存,这意味着它们不会阻止垃圾收集,以防没有其他对该对象的引用。” 来源
(另请参阅我的帖子 ECMAScript Harmony 首次与 Firefox 一起发布...)
A weak reference is a special object containing an object-pointer, but does not keep that object alive.
One application of weak references are implemented in Weak Maps:
“The experienced JavaScript programmer will notice that this API could be implemented in JavaScript with two arrays (one for keys, one for values) shared by the 4 API methods. Such an implementation would have two main inconveniences. The first one is an O(n) search (n being the number of keys in the map). The second one is a memory leak issue. With manually written maps, the array of keys would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are held “weakly”, which means that they do not prevent garbage collection in case there would be no other reference to the object.” Source
(See also my post when ECMAScript Harmony was first released with Firefox... )
WeakMap
WeakMap 基本上允许您拥有一个键不是字符串的哈希表。
因此,您可以将键设置为,即
[1]
,然后可以说Map.get([1])
来自 MDN 的示例:
它存在的原因是:
显然,模拟弱映射会导致内存泄漏。我不知道这些内存泄漏的细节。
WeakMap
WeakMaps basically allow you to have a HashTable with a key that isn't a String.
So you can set the key to be, i.e.
[1]
and then can sayMap.get([1])
Example from the MDN:
The reason for its existance is:
Apparently emulating weakmaps causes memory leaks. I don't know the details of those memory leaks.
WeakMap 允许使用对象作为键。
它没有任何方法可以知道地图的长度。长度始终为 1。
键不能是原始值
关于使用对象作为键的一个注意事项是,由于默认情况下所有对象都是 JavaScript 中的单例,因此我们应该创建一个对象引用并使用它。
这是因为当我们创建匿名对象时它们是不同的。
因此,在以下场景中,我们不能期望获得该值
,并且以下代码片段将按预期工作。
WeakMap allows to use objects as keys.
It does not have any method to know the length of the map. The length is always 1.
The key can't be primitive values
A word of caution about using object as key is, since all the objects are by default singletons in JavaScript we should be creating an object reference and use it.
This is because when we create anonymous objects they are different.
So in the following scenario, we can't expect to get the value
And the following snippet will work as expected.