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

Class-Block scope declaration #76

Closed
shannon opened this issue Jan 26, 2018 · 4 comments
Closed

Class-Block scope declaration #76

shannon opened this issue Jan 26, 2018 · 4 comments

Comments

@shannon
Copy link

shannon commented Jan 26, 2018

I have another proposal that is opposed to my previous proposal #75. This proposal goes in the opposite direction to the other paradigm of having record-like syntax.

Normally with block scoping we can do something like this:

const x = 'x';
{
  const x = 'different x';
  const y = 'y';
  console.log(x); // outputs 'different x'
  console.log(y); // outputs 'y'
}
console.log(x); // outputs 'x'
console.log(y); // Uncaught ReferenceError: y is not defined

This makes sense and we all understand it.

Class declaration is not quite like block scoping in that we don't use const or let but if we were to add an internal block scope like syntax to classes we could treat the internal properties as private instance properties. For example:

class Foo {
    x = "I'm pubic";

    {
        y = "I'm private";
        privateMethod() { 
          return y;
        }
    }

    publicMethod() {
       return privateMethod() + this.x;
    }
}

To describe how this would work we would say this block scope is created for each instance and can be referenced from all class methods. The block scope syntax would mirror the class declaration syntax and internally you would treat all properties within the block scope as you treat regular class properties with respect to initiliazers. Block scoped methods would be bound to the class instance but getters/setters wouldn't make any sense in this case so they can be prohibited.

This and #75 are two very different proposals but each try to align this proposal with the way developers understand JS to work today. This proposal doesn't offer a way to iterate or access private properties via a variable but it does remove the need for destructuring all together (which would be my biggest complaint about the current proposal).

@littledan
Copy link
Member

One of the biggest issues with basing privacy on lexical scope is that it is unclear how we would support accessing private fields from other instances of the same class. Do you have an idea for how to provide this capability?

@shannon
Copy link
Author

shannon commented Jan 26, 2018

@littledan you are correct, that would be impossible because it requires a non record-like syntax.

@littledan
Copy link
Member

OK, fine to close this issue then?

@shannon
Copy link
Author

shannon commented Jan 26, 2018

Sure we can close it.

@shannon shannon closed this as completed Jan 26, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants