Use cases for WeakMap

Allen Wirfs-Brock allen at
Sun May 15 17:03:30 PDT 2011

On May 15, 2011, at 3:50 PM, Brendan Eich wrote:

> On May 15, 2011, at 3:48 PM, Oliver Hunt wrote:
>> On May 15, 2011, at 3:47 PM, Boris Zbarsky wrote:
>>> On 5/15/11 2:20 PM, Rick Waldron wrote:
>>>> Thanks Brendan, I was looking for something that was representative of
>>>> Boris's use-case
>>> A typical example is an extension wanting to associate some state with a DOM element or a Window without polluting the DOM.  For example, Adblock Plus wants to store some state per-element so that it knows when it's in the middle of unblocking something so it'll allow the load through for that one thing only.  Firebug wants to store some state per-window (e.g. script bodies, etc) and discard it when the window goes away.
>> Which is a use case private names would achieve much more succinctly than weakmaps.
> Not if the object is frozen.
> Unless you then overspecify private names *as* weak maps, in which case we are going in circles :-P.
> /be

From a object design perspective there is a big difference between using a side-table to associate supplementary information with an object and adding a property to an object.  This difference is independent of issues like weakness of the table or visibility of the property.

An object is suppose to represent a cohesive abstraction The building blocks of a JS object abstraction are its properties. You should only add properties to an object if they contribute to a cohesive extension of the object's abstraction. If you are simply  tracking an object or using it as data to in the context of some other abstraction you should be extending to the object properties.  Instead the tracking mechanism or additional data should be part of the consuming abstraction, perhaps represented as some sort of "side table".

 There are only a few caveats to the above.  If the abstraction is some sort of generic data collection (eg, an Array) that directly exposes its content as properties, then of course you can add properties if you are adding to the collection.  Similarly, if an object exposed as part of its core abstraction some sort of open-end annotation or extension mechanism then it should be used as intended.  Finally, you may be forced to use a "side-table" for what should logically be a property level extension to an if you are not allowed to extend the original object.  


More information about the es-discuss mailing list