Encapsulation is a fundamental concept in object-oriented programming (OOP) that helps us create more organized and maintainable code. In JavaScript, we can achieve encapsulation using classes, which were introduced in the ES6 (ECMAScript 2015) specification.
Classes in JavaScript provide a way to create objects with their own properties and methods, and they also allow us to encapsulate data and behavior within these objects. This means that we can hide the internal implementation details of an object and expose only the necessary interface, making our code more modular and easier to work with.
Let’s dive into some practical examples to see how we can use classes to achieve encapsulation in JavaScript.
Creating a Simple Class
Suppose we want to create a BankAccount
class that represents a bank account. We can define the class like this:
class BankAccount {
constructor(owner, balance) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
}
withdraw(amount) {…