Private members in classes

Andrea Giammarchi andrea.giammarchi at gmail.com
Fri Nov 11 09:34:22 UTC 2016


FWIW I think Axel WeakMap example is just one of the variant but not the
optimal one.

Following how I'd use WeakMap to store private references.

It uses only one WeakMap and it's less prone to forgotten updates (re-set)

```js
const _Countdown = new WeakMap();
class Countdown {
    constructor(counter, action) {
        // you set only once
        _Countdown.set(this, {
            counter,
            action
        });
    }
    dec() {
        // you get every time without needing
        // to set again (early return footgun proof)
        const _pvt = _Countdown.get(this);
        if (_pvt.counter < 1) return;
        _pvt.counter--;
        if (_pvt.counter === 0) {
            _pvt.action();
        }
    }
}
```

Best Regards



On Fri, Nov 11, 2016 at 8:48 AM, Alex Vincent <ajvincent at gmail.com> wrote:

> Hiding private values is something that I've been thinking a lot about in
> my es7-membrane project. [1]  Unfortunately, I've been overloaded with my
> full-time job and university courses this quarter, and the soonest I can
> return to it will probably be late December.  For about two weeks, until
> the next quarter begins.  I'm really overloaded...
>
> [1] https://github.com/ajvincent/es7-membrane/issues/19
>
> Alex Vincent
> Hayward, CA, U.S.A.
>
> --
> "The first step in confirming there is a bug in someone else's work is
> confirming there are no bugs in your own."
> -- Alexander J. Vincent, June 30, 2001
>
> _______________________________________________
> 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/20161111/fd105e89/attachment.html>


More information about the es-discuss mailing list