proposal-class-fields icon indicating copy to clipboard operation
proposal-class-fields copied to clipboard

Private member access from static methods

Open rijnhard opened this issue 6 years ago • 5 comments

I did search to see if I could find the answer but no luck.

The question is simple, is this supposed to work? Because it should with babel as it stands, if it does then it should be noted somewhere more obvious.

class Test {
    #foo = 'bar';

    /**
     * @param {Test} t
     */
    static baz(t) {
        t.#foo = 'baz';
    }

    get foo() {
        return this.#foo;
    }
}

const t = new Test();

console.info(t.foo); // prints 'bar'
Test.baz(t);
console.info(t.foo); // prints 'baz'

rijnhard avatar May 20 '19 16:05 rijnhard

Yes, this works. The MDN documentation for this feature is currently in progress; sounds like we should call out cases like this.

littledan avatar May 20 '19 16:05 littledan

It does. You can refer to a private field anywhere within the class body.

This matches other languages like Java.

bakkot avatar May 20 '19 16:05 bakkot

@littledan cases like this should definitely be called out. Thank you. It was a surprise to see it working, but (from previous experience) I didn't want to rely on undocumented behaviour with anything not in stage 4.

rijnhard avatar May 20 '19 17:05 rijnhard

@rijnhard Can I ask why it was a surprise to see it working?

bakkot avatar May 20 '19 18:05 bakkot

@rijnhard Can I ask why it was a surprise to see it working?

@bakkot Honestly, because I didn't expect it to have access to the context. I use WeakMaps and WeakSets quite a bit, and usually in cases where I want to create a private scope. (If I want anything other than fully private I abuse Object.defineProperty). From skimming the docs and comments I saw the implementation was based on WeakSets. Added to that I know that private variables are private, not protected, so no access from child classes, and for some reason, in my mind, I equated prototype methods to being in a different scope.

tl;dr I didn't think prototype methods could have access because of guesses I made from half of the info I read about implementation.

So I just knew enough to make a bad guess, lol.

rijnhard avatar May 21 '19 07:05 rijnhard