Private members in classes

# jeremy nagel (7 years ago)

Are there any proposals currently to allow private members in classes? Current options (e.g. www.2ality.com/2016/01/private-data-classes.html) don't feel that clean. Would be nice to have Java style private members.

Jeremy Nagel 0414 885 787

# Aaron Powell (7 years ago)

See: tc39/proposal-private-fields

From: es-discuss [mailto:es-discuss-bounces at mozilla.org] On Behalf Of jeremy nagel Sent: Tuesday, 8 November 2016 16:35 To: es-discuss at mozilla.org Subject: Private members in classes

Are there any proposals currently to allow private members in classes? Current options (e.g. www.2ality.com/2016/01/private-data-classes.html) don't feel that clean. Would be nice to have Java style private members.

Jeremy Nagel 0414 885 787

# Alex Vincent (7 years ago)

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] ajvincent/es7-membrane#19

Alex Vincent Hayward, CA, U.S.A.

# Andrea Giammarchi (7 years ago)

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)

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