Use cases for WeakMap

David Bruant david.bruant at
Sat May 14 15:25:48 PDT 2011

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 = {};
    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

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.


More information about the es-discuss mailing list