Use cases for WeakMap

Andreas Gal gal at mozilla.com
Sat May 14 15:48:19 PDT 2011


If you want to self-host Date objects in JS you can use a WeakMap to store the [[Value]] for each Date object (similar to private names, the Date object is the key). The same goes for self-hosted DOM implementations (the content-facing wrapper is the key used to look up the internal object holding the underlying DOM node state).

Andreas

On May 14, 2011, at 3:37 PM, Oliver Hunt wrote:

> It's not that they're impossible, it's that they all reduce to a strong map with automatic deletion, rather than "WeakMap".
> 
> Take any form of weak cache, say for example you want to cache the object representation that's the result of an XHR (or some such)
> 
> eg.  you want to do
> 
> function getObject(url) {
>    var result = myCache.get(url);
>    if (result)
>       return result;
>    result = Object.freeze(JSON.parse(loadURLWithSynchXHR(url).responseText));
>    myCache.set(url, result);
>    return result;
> }
> 
> Except you this doesn't work, because the map needs to have an object key, so the string is not allowed, we have to do new String(url) or some such as the key, so for a use case like this we need a map from string primitive to String object, so making the map a strong map.
> 
> Can you provide a use case where you have an object key as the usual programming idiom?
> 
> --Oliver
> 
> On May 14, 2011, at 3:25 PM, Andreas Gal wrote:
> 
>> 
>> Can you describe those common use cases, and how they are impossible with the current specification?
>> 
>> Andreas
>> 
>> On May 14, 2011, at 3:05 PM, Oliver Hunt wrote:
>> 
>>> The more I read the WeakMap spec, the more it seems to prevent the common use cases I know of.  Could someone give a few examples of problems the current weakmap spec solves?
>>> 
>>> --Oliver
>>> 
>>> _______________________________________________
>>> es-discuss mailing list
>>> es-discuss at mozilla.org
>>> https://mail.mozilla.org/listinfo/es-discuss
>> 
> 



More information about the es-discuss mailing list