Skip to content

Instantly share code, notes, and snippets.

@AnsonH
Last active September 9, 2021 12:38
Show Gist options
  • Save AnsonH/8c308073d8bb3032e5b82c189e6c637f to your computer and use it in GitHub Desktop.
Save AnsonH/8c308073d8bb3032e5b82c189e6c637f to your computer and use it in GitHub Desktop.
Javascript Tip #3 - Class private properties and methods
/* Tweet: https://twitter.com/AnsonH_/status/1435945599367479303 */
class Student {
#gpa; // 1. Declare private property using the # sign
constructor(gpa) {
this.#gpa = gpa; // 2. Add this private property to class instance
}
// Private method
#setGpa(newGpa) {
this.#gpa = newGpa;
}
}
const tom = new Student(2.0);
console.log(tom); // undefined (since tom.gpa is private field)
tom.gpa = 4.3; // tom's private gpa property will not change
tom.setGpa(4.3); // TypeError: tom.setGpa is not a function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment