Skip to content
This repository has been archived by the owner on Jan 25, 2022. It is now read-only.

Private member access from static methods #239

Open
rijnhard opened this issue May 20, 2019 · 5 comments
Open

Private member access from static methods #239

rijnhard opened this issue May 20, 2019 · 5 comments

Comments

@rijnhard
Copy link

rijnhard commented May 20, 2019

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
Copy link
Member

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

@bakkot
Copy link
Contributor

bakkot commented May 20, 2019

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

This matches other languages like Java.

@rijnhard
Copy link
Author

@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
Copy link
Contributor

bakkot commented May 20, 2019

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

@rijnhard
Copy link
Author

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

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants