Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active April 10, 2018 22:07
Show Gist options
  • Save rauschma/f60c38f2ed485dad292431107343eb05 to your computer and use it in GitHub Desktop.
Save rauschma/f60c38f2ed485dad292431107343eb05 to your computer and use it in GitHub Desktop.
Fields with arbitrarily scoped privacy

Fields with arbitrarily scoped privacy

Info on private fields: http://2ality.com/2017/07/class-fields.html

Q&A

  • Why the prefix #?
    • You define keys and these keys additionally work completely differently from property keys.
  • Is the keyword private necessary?
    • It could be omitted (first mention declares), but I like the distinction between declaration and mention.
// Can only be used within this scope
private #data;
class StringBuilder {
// Accessible within this scope
#data = '';
add(str) {
this.#data += str;
}
}
function toString(sb) {
return this.#data;
}
// Can only be used within this scope
private #data;
function create() {
return {
// Only accessible within this scope
#data: '',
};
}
function add(sb, str) {
sb.#data += str;
}
function toString(sb) {
return sb.#data;
}
class StringBuilder {
private #data = '';
add(str) {
this.#data += str;
}
toString() {
return this.#data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment