Private symbols as WeakMap sugar

Claude Pache claude.pache at
Mon Jan 21 01:05:42 PST 2013

Le 16 janv. 2013 à 09:11, David Bruant <bruant.d at> a écrit :

> Hi,
> This is an idea naturally derived of all the current discussions about WeakMaps and Private symbols. The proposal is easily summarized by these lines of code:
>    var wm = new WeakMap();
>    var o = {};
>    o[wm] = 12 // desugars to wm.set(o, 12)
>    var a = o[wm]; // desugars to wm.get(o);
>    wm in o // desugars to wm.has(o);
>    delete o[wm] // desugars to wm.delete(o);
> <snip>


I've just thought of a fundamental flow in the idea of using of weak maps instead of  private symbols, which I believe is enough for forcing to forget that idea, at least on a language design level.

(Note: I have not reread all what have been posted on this list on the subject since then, so I am not sure that someone has not already raised that objection.)

Weak maps and private symbols have completely different goals, and conflating the two features into one can (and, as I'll show,  will) lead to conflict of interest in designing the API. Weak maps are designed for better memory management, while private symbols are designed for better encapsulation. The key difference of philosophy between the two features is:

* In weak maps, you ***need not*** have access to the value if you don't have access to the key.
* With private symbols used as property keys,  you ***must not*** have access to the property value if you don't have access to the symbol.

It is just a happenstance that, in our case "need not" mostly implies "do not". The problem is that it is only "mostly". Indeed:

It is very reasonable to have a -clear() method on WeakMaps, which delete all relations defined by the weak map, in situation where you know that you won't need these mappings any more, but it would be impractical to either enumerate all the keys, or to wipe all references to the weak map. Good for memory management.

On the other hand, you certainly do not want a ".revoke()" method available on every private symbols, which wipe all properties which use that key as private symbol, even on objects to which you are not allowed to have access. Bad for encapsulation.

There is no fundamental problem to use a feature for something very different that it was not designed for. But before sanctioning such a use in a language design, conflict of interest between the two intended use must be carefully considered.


More information about the es-discuss mailing list