Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Private fields are truly hidden class properties that can't be accessed from outside the class. Use # prefix to make fields private!
# symbol marks fields as private - no one outside can access them, not even subclasses!class User {
name = 'Alice'; // Public
}
const user = new User();
console.log(user.name); // 'Alice' ✓
user.name = 'Bob'; // Can change ✓class User {
#password = 'secret'; // Private
}
const user = new User();
console.log(user.#password); // Error! ✗
user.#password = 'new'; // Error! ✗Truly hidden data
Methods can also be private - perfect for internal helper functions
class Validator {
#isValidEmail(email) { // Private method
return email.includes('@') && email.includes('.');
}
validateUser(email) { // Public method
if (this.#isValidEmail(email)) {
return 'Valid email';
}
return 'Invalid email';
}
}
const validator = new Validator();
console.log(validator.validateUser('test@example.com')); // 'Valid email'
// Cannot call private method
validator.#isValidEmail('test'); // SyntaxError!Hidden helper functions
Use getters/setters to provide controlled access to private fields
class Temperature {
#celsius;
constructor(celsius) {
this.#celsius = celsius;
}
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (value < -273.15) {
throw new Error('Below absolute zero!');
}
this.#celsius = value;
}
}
const temp = new Temperature(25);
console.log(temp.celsius); // 25
temp.celsius = 30; // ✓ Valid
temp.celsius = -300; // ✗ Error!Validated access
Combine static and private for hidden class data
class Database {
static #connection = null; // Static private
static #maxConnections = 5;
static connect() {
if (!this.#connection) {
this.#connection = 'Connected';
console.log('Database connected');
}
}
static getStatus() {
return this.#connection ? 'Connected' : 'Disconnected';
}
}
Database.connect();
console.log(Database.getStatus()); // 'Connected'
// Cannot access static private fields
// Database.#connection; // Error!Singleton pattern with privacy
this.field - Accessible everywherethis._field - Not enforced, just conventionthis.#field - Truly hidden, enforced by language ✓