tc39 / proposal-class-fields

Orthogonally-informed combination of public and private fields proposals
https://arai-a.github.io/ecma262-compare/?pr=1668
1.72k stars 113 forks source link

Private member access from static methods #239

Open rijnhard opened 5 years ago

rijnhard commented 5 years ago

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'
littledan commented 5 years ago

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

bakkot commented 5 years ago

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

This matches other languages like Java.

rijnhard commented 5 years ago

@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.

bakkot commented 5 years ago

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

rijnhard commented 5 years ago

@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.