Use cases for WeakMap

Rick Waldron waldron.rick at gmail.com
Sat May 14 15:29:54 PDT 2011


This is a gist that David Bruant created for me with regard to conversation
in the Property Fixing thread: https://gist.github.com/970812

<https://gist.github.com/970812>Seen here:
http://www.mail-archive.com/es-discuss@mozilla.org/msg07167.html

Rick

On Sat, May 14, 2011 at 6:25 PM, David Bruant <david.bruant at labri.fr> wrote:

> Le 15/05/2011 00:05, Oliver Hunt a écrit :
> > The more I read the WeakMap spec, the more it seems to prevent the common
> use cases I know of.
> What are the use cases you know of? How are they prevented by the
> current spec?
>
> >  Could someone give a few examples of problems the current weakmap spec
> solves?
> In my opinion, having a key->value map indexed on object identities
> which has O(log(n)) lookup is a win by itself. Weakness is a plus.
>
> I don't know if it's a problem, but WeakMaps with getters/setters allow
> a form of inheritance that has not really been possible before (it was
> with getter/setters and arrays, but with almost unavoidable memory leaks).
> ----
> var o = {};
> (function(){
>    var wm = WeakMap();
>
>    function get(){
>        return wm.get(this);
>    }
>
>    function set(val){
>        wm.set(this, val);
>    }
>
>    Object.defineProperty(o, "a", {get:get, set:set});
> })();
>
> var oo = Object.create(o);
> oo.a = 1;
>
> var oo2 = Object.create(o);
> oo2.a = 2;
>
> console.log(oo.a); // 1;
> console.log(oo2.a); // 2
> // but still:
> console.log(Object.getOwnPropertyDescriptor(oo, "a")); // undefined
> console.log(Object.getOwnPropertyDescriptor(oo2, "a")); // undefined
> // On FF nightly, this is not undefined, but I'd say it's due to
> https://bugzilla.mozilla.org/show_bug.cgi?id=636989
> ----
>
> Other may disagree, but I like this pattern, because it keeps properties
> "at the layer they belong to" rather than making the own layer a messy bag.
>
> David
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20110514/cb5d4661/attachment.html>


More information about the es-discuss mailing list