WeakMap在EcmaScript5中的实现? [英] WeakMap implementation in EcmaScript5?
问题描述
我已经跨越 JavaScript库实施跨浏览器 WeakMap 在 ES5 中。 (WeakMap将针对 ES6 计划。)
I've run across a JavaScript library that implement a cross-browser WeakMap in ES5. (WeakMap is slated for ES6.)
如果JavaScript语言本身没有支持,这可能如何工作?
How can this possibly work without support in the JavaScript language itself?
编辑:要清楚,我指的是一个弱地图,而不是一个常规的地图。我使用Chrome的分析器测试了这个项目,并且密钥没有强引用。他们得到GC,而不必将它们从WeakMap中删除。
Just to be clear, I'm referring to a Weak Map, not a regular Map. I tested this project out using Chrome's profiler and the keys are not held by strong references. They get GC'ed without having to remove them from the WeakMap.
推荐答案
我花了一段时间来挖掘代码,但是那么它打了我:键本身用于存储对该值的引用。
It took me a while to grok the code, but then it hit me: the key itself is used to store a reference to the value.
例如,几个层到 set
它是
defProp(obj, globalID, { value: store });
其中 defProp
已被定义为 Object.defineProperty
, obj
是关键, globalID
是一个guid和 store
是一个包含该值的存储对象。
where defProp
has been defined to be Object.defineProperty
, obj
is the key, globalID
is a guid and store
is a storage object that contains the value.
然后在中获取
它查找
obj [globalID];
这很聪明。 WeakMap实际上并不包含任何引用(weak或other) - 它只是设置一个秘密存储值的策略。使用 Object.defineProperty
意味着你不会意外发现价值存储 - 你必须知道查看它的魔术指南。
This is very clever. The WeakMap doesn't actually contain a reference to anything (weak or otherwise)-- it just sets up a policy of where to secretly store the value. The use of Object.defineProperty
means that you won't accidentally discover the value storage-- you have to know the magic guid to look it up.
由于密钥直接引用该值(并且WeakMap不参考它),当所有对密钥的引用都消失时,它就像正常的GC一样。
Since the key directly refers to the value (and the WeakMap doesn't refer to it), when all references to the key are gone, it gets GCed like normal.
这篇关于WeakMap在EcmaScript5中的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!