

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Private Properties
incomplete
3: Static Methods
incomplete
4: Getters and Setters
incomplete
5: Inheritance
incomplete
6: Super
incomplete
This lesson's interactive features are locked, please to keep using them
By default, all properties of a class are public, meaning they can be accessed and modified from outside the class. Here's an example:
class Movie {
constructor(title, rating) {
this.title = title;
this.rating = rating;
}
}
const matrixMovie = new Movie("The Matrix", 9.5);
console.log(matrixMovie.title);
// The Matrix
matrixMovie.title = "The Matrix Reloaded";
console.log(matrixMovie.title);
// The Matrix Reloaded
Maybe we don't want our title to be able to be changed anywhere in our code. We can make it private by prefixing it with a hash # and declaring it at the top of the class:
class Movie {
#title;
constructor(title, rating) {
this.#title = title;
this.rating = rating;
}
}
const matrixMovie = new Movie("The Matrix", 9.5);
console.log(matrixMovie.#title);
// Uncaught SyntaxError: Private field '#title' must be declared in an enclosing class
Private properties can still be used from within the class:
class Movie {
#title;
constructor(title, rating) {
this.#title = title;
this.rating = rating;
}
getTitleAllCaps() {
const allCaps = this.#title.toUpperCase();
return allCaps;
}
}
const matrixMovie = new Movie("The Matrix", 9.5);
console.log(matrixMovie.getTitleAllCaps());
// THE MATRIX
Encapsulation in JavaScript is typically enforced at two levels:
# for private fieldsTextio messages have a createdAt field that stores the date the message was created. In order to avoid accidentally altering the creation date, change the createdAt field from a public field to a private field.