Welcome! Today's subject is Encapsulation, a cornerstone of Object-Oriented Programming (OOP). Encapsulation bundles data and the operations that we perform on them into one unit, namely an object. It guards data against unwanted alterations, ensuring the creation of robust and maintainable software.
Prepare yourself for an exciting journey as we delve into how encapsulation works in JavaScript and explore the vital role it plays in data privacy.
Starting with the basics, Encapsulation is similar to packing data and the methods that modify this data into a single compartment known as a class
. It safeguards the data in an object from external interference.
To illustrate, consider a JavaScript class
representing a bank account. Without encapsulation, the account balance could be directly altered. With encapsulation, however, the balance can only change through specified methods, like depositing or withdrawing.
Encapsulation restricts direct access to an object's data and prevents unwanted data alteration. This principle is comparable to window blinds, allowing you to look out while preventing others from peeping in.
In JavaScript, encapsulation pertains to private and public fields, which are integral to data privacy. Private fields, prefixed with #, warrant caution while being manipulated. Constructors
are special methods used for initializing these fields and setting up the initial state of an object. They are automatically called when an object is created from a class.
To illustrate, let's consider a JavaScript class
named Person
, which includes a private field #name
.
JavaScript1class Person { 2 #name; // Private field 3 4 constructor(name) { 5 this.#name = name; 6 } 7 8 getName() { // Accessor method 9 return this.#name; 10 } 11} 12 13const person = new Person('Alice'); 14console.log(person.getName()); // Accessing private field via accessor method. Output: Alice 15console.log(person.#name); // Error: Private field '#name' must be declared in an enclosing class
In this example, #name
is private, and getName()
enables us to access #name
. However, we specify that the name can't be changed, as we don't provide a proper method for that.
In JavaScript, all class
members are public by default. To designate a field as private, we prefix it with #
.
Within encapsulation, JavaScript uses getter and setter methods to access or modify private fields. In a class
, the getter method retrieves the field's value, and the setter method alters it. Let's illustrate this.
JavaScript1class Dog { 2 #name; // Private field 3 4 constructor(name) { 5 this.#name = name; 6 } 7 8 set name(newName) { // Setter method 9 this.#name = newName; 10 } 11 12 get name() { // Getter method 13 return this.#name; 14 } 15} 16 17const myDog = new Dog('Max'); 18myDog.name = 'Buddy'; 19console.log(myDog.name); // Output: Buddy
Here, set name()
and get name()
serve as the setter and getter methods, respectively, for the private field #name
.
Let's apply the principle of encapsulation to our BankAccount
class, which includes private fields like account number and balance, along with public methods for withdrawals, deposits, and balance checks.
JavaScript1class BankAccount { 2 #accountNo; 3 #balance; 4 5 constructor(accountNo, balance) { 6 this.#accountNo = accountNo; 7 this.#balance = balance; 8 } 9 10 withdraw(amount) { 11 this.#balance -= amount; 12 } 13 14 deposit(amount) { 15 this.#balance += amount; 16 } 17 18 checkBalance() { 19 return this.#balance; 20 } 21} 22 23const account = new BankAccount(1, 500); 24account.withdraw(100); 25account.deposit(50); 26console.log(account.checkBalance()); // Prints: 450
In the above code, the BankAccount
class encapsulates account details, and the public methods manipulate the balance in a controlled way.
Admirable! Now it's your turn to apply what you've learned by practicing encapsulation in JavaScript. Remember, practice enhances your comprehension. Enjoy coding!