Skip to content

Instantly share code, notes, and snippets.

@jridgewell
Forked from rauschma/_private-fields-faq.md
Last active February 20, 2018 21:54
Show Gist options
  • Save jridgewell/c59e6ff1a3f7700ec26b0ca322643ea2 to your computer and use it in GitHub Desktop.
Save jridgewell/c59e6ff1a3f7700ec26b0ca322643ea2 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;
}
function create() {
return {
private #data: '',
add(str) {
this.#data += str;
},
toString() {
return this.#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