[PROPOSAL] "use" keyword

Tab Atkins Jr. jackalmage at gmail.com
Fri Jul 25 13:29:51 PDT 2014


On Fri, Jul 25, 2014 at 12:56 PM, Michaël Rouges
<michael.rouges at gmail.com> wrote:
> Hi David.
>
> Sure... I make a library that that needs to share a private variable with
> all methods
> of an instance passed by arguments on my lib' method.
>
> ```
> var lib;
>
> (function () {
>     var shared;
>
>     shared = 'a shared value';
>
>     lib = {
>         method: function method(foreignObject) {
>             var property;
>
>             for (property in foreignObject) {
>                 if (foreignObject.hasOwnProperty('property') {
>                     if (typeof foreignObject === 'function') {
>                         // how to pass the "shared" variable
>                         // preserving the inside this in foreignObject
> methods
>                         // and without to touch the methods args?
>                     }
>                 }
>             }
>         }
>     };
> }());```

Ah, so you've got a "private" variable (declared in a closure) that
you want to share with other objects which aren't created in the same
closure.

This is what Symbols/WeakMaps were made for.  Precisely how to use
them depends on exactly what you're going for and what your
constraints are, but I'm confident you could bodge something together
with a WeakMap without too much trouble.

~TJ


More information about the es-discuss mailing list