Today you will learn:
#)this nuancesBy the end, you will create robust classes with encapsulation and methods.
Use the class keyword to define objects:
class Person {
#age;
constructor(name, age) {
this.name = name;
this.#age = age;
}
getAge() {
return this.#age;
}
}
const john = new Person("John", 30);
console.log(john.getAge()); // 30
Encapsulate access to private fields:
class Person {
#age;
constructor(name, age) {
this.name = name;
this.#age = age;
}
get age() {
return this.#age;
}
set age(value) {
if(value >= 0) this.#age = value;
}
}
const alice = new Person("Alice", 25);
console.log(alice.age); // 25
alice.age = 30;
console.log(alice.age); // 30
Methods inside classes use this to access properties:
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hi, I'm ${this.name}`);
}
}
const bob = new Person("Bob");
bob.greet(); // Hi, I'm Bob
class Person {
#age;
constructor(name, age) {
this.name = name;
this.#age = age;
}
getAge() { return this.#age; }
}
const john = new Person("John", 30);
console.log(john.getAge());
Create a BankAccount class:
#balancedeposit(amount) and withdraw(amount)Example:
class BankAccount {
#balance;
constructor(initialBalance = 0) {
this.#balance = initialBalance;
}
deposit(amount) {
if(amount > 0) this.#balance += amount;
}
withdraw(amount) {
if(amount <= this.#balance) this.#balance -= amount;
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
console.log(account.getBalance()); // 120