Skip to content

Instantly share code, notes, and snippets.

@littledan
Last active February 12, 2019 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save littledan/d3030534cf96075d47228955828f932e to your computer and use it in GitHub Desktop.
Save littledan/d3030534cf96075d47228955828f932e to your computer and use it in GitHub Desktop.
// In the following code, take `private` and `friend` to be extremely early strawperson names
private #x; // Declare a private name
let obj = { outer #x: 1 };
class MyClass {
outer #x;
constructor(x) { this.#x = x }
}
// #x can be accessed from functions in the lexical scope of the `private` declaration
function getX(obj) {
return obj.#x;
}
getX(new MyClass(2)); // 2
getX(obj); // 1
// Usable from destructuring
let { outer #x: a } = obj; // a = 1
// Can be used for friend methods as well
{
private #y;
class Z {
outer #y() {
alert('hi');
}
}
new Z().#y(); // alert hi
}
// Cannot be accessed outside block scope--early error
let y = {outer #y: 2}; // SyntaxError
@littledan
Copy link
Author

littledan commented Jan 4, 2018

Alternate, if we force private to be in class private field and method declarations, and a missing private makes it a friend.

However, this doesn't work for the same reasons @wycats explained when private fields got to Stage 3: It has strange syntax when interacting with decorators, where you'd want to do things like @reader private #field and @protected private #field, which are both wordy and appear non-sensical. It's better to continue with the current syntax for private fields, which don't have an explicit private.

// In the following code, take  `private` and `friend` to be extremely early strawperson names

private #x;  // Declare a private name

let obj = { #x: 1 };

class MyClass {
  #x;  // Visible to the outer `private #x` declaration
  private #y;  // local to the class
  private #method() {  } // local to the class
  constructor(x) { this.#x = x; this.#y = y }
}

// #x can be accessed from functions in the lexical scope of the `private` declaration
function getX(obj) {
  return obj.#x;
}

getX(new MyClass(2));  // 2
getX(obj);  // 1

// Usable from destructuring
let { #x: a } = obj;  // a = 1
    }

// Can be used for friend methods as well

{
  private #y;
  class Z {
    #y() {
      alert('hi');
    }
  }
  
  new Z().#y();  // alert hi
}

// Cannot be accessed outside block scope--early error
let y = {#y: 2}; // SyntaxError

@ByteEater-pl
Copy link

Can it be accessed in different classes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment