9.1 Core Concepts
Encapsulation is one of the key concepts of Object-Oriented Programming (OOP), allowing you to hide the internal implementation details of an object and provide access to these details through well-defined interfaces. This helps enhance security and simplifies code management.
Benefits of encapsulation:
- Data Hiding: Encapsulation allows you to hide the internal implementation details and provide access only to necessary methods and properties. This prevents incorrect use of objects and improves code security.
- Access Control: Encapsulation enables control over access to data and methods, allowing to change the object's internal state only through specified methods.
- Maintainability: Encapsulation improves code maintainability as changes in implementation do not affect the external interface of the class. This allows making changes in the implementation without altering the code using the class.
- Improved Testing: Encapsulation allows isolating the internal implementation of an object, making unit testing easier and reducing the likelihood of side effects.
In JavaScript, encapsulation is achieved using methods and properties, and starting with ES2022, private fields and methods have also become available.
9.2 Encapsulation with Closures
Before the introduction of private fields in ES2022, encapsulation in JavaScript was often achieved using closures.
Example:
- The
count
variable is only accessible inside thecreateCounter
function and is not available from outside - The
increment
,decrement
, andgetCount
methods can interact with the privatecount
variable
function createCounter() {
let count = 0; // private variable
return {
increment() {
count++;
console.log(count);
},
decrement() {
count--;
console.log(count);
},
getCount() {
return count;
}
};
}
const counter = createCounter();
counter.increment(); // 1
counter.increment(); // 2
console.log(counter.getCount()); // 2
counter.decrement(); // 1
9.3 Private Fields in ES2022
ES2022 introduced private fields and methods, which are declared using the #
symbol. Private fields and methods cannot be accessed or modified outside the class.
Example:
- Private fields
#name
and#age
are declared with the#
symbol - The
getName
,getAge
,setName
, andsetAge
methods allow interacting with private fields - Attempting to access private fields from outside the class results in an error
class Person {
#name; // private field
#age; // private field
constructor(name, age) {
this.#name = name;
this.#age = age;
}
getName() {
return this.#name;
}
getAge() {
return this.#age;
}
setName(name) {
this.#name = name;
}
setAge(age) {
if (age > 0) {
this.#age = age;
}
}
}
const person = new Person('Alice', 30);
console.log(person.getName()); // "Alice"
console.log(person.getAge()); // 30
person.setName('Bob');
person.setAge(25);
console.log(person.getName()); // "Bob"
console.log(person.getAge()); // 25
console.log(person.#name); // Error: private field is inaccessible
9.4 Private Methods
Private methods can also be declared using the #
symbol and be inaccessible from outside the class.
Example:
- The private field
#balance
and private method#logTransaction
are used to manage theBankAccount
object's state - The private method
#logTransaction
is called inside the publicdeposit
andwithdraw
methods to log transactions
class BankAccount {
#balance;
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
this.#logTransaction('deposit', amount);
}
}
withdraw(amount) {
if (amount > 0 && amount <= this.#balance) {
this.#balance -= amount;
this.#logTransaction('withdraw', amount);
}
}
getBalance() {
return this.#balance;
}
#logTransaction(type, amount) {
console.log(`Transaction: ${type} ${amount}`);
}
}
const account = new BankAccount(1000);
account.deposit(500); // "Transaction: deposit 500"
console.log(account.getBalance()); // 1500
account.withdraw(200); // "Transaction: withdraw 200"
console.log(account.getBalance()); // 1300
account.#logTransaction('test', 100); // Error: private method is inaccessible
GO TO FULL VERSION