Last active
September 9, 2021 12:38
-
-
Save AnsonH/8c308073d8bb3032e5b82c189e6c637f to your computer and use it in GitHub Desktop.
Javascript Tip #3 - Class private properties and methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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