Object-Oriented Programming (OOP) is a programming paradigm that uses objects and their interactions to design applications and computer programs. JavaScript, although primarily a functional programming language, supports OOP concepts through classes and prototypes. In this article, we will explore the core concepts of OOP in JavaScript and how to implement them effectively.
Core Concepts of Object-Oriented Programming
1. Class
A class is a blueprint for creating objects. It defines the properties and methods that an object will have. In JavaScript, classes are defined using the class
keyword.
// Define a class
class Car {
constructor(model, year) {
this.model = model;
this.year = year;
}
// Method
getModel() {
return this.model;
}
}
2. Object
An object is an instance of a class. It is created from a class and contains the properties and methods defined in the class.
// Create an object
const myCar = new Car('Toyota', 2022);
console.log(myCar.getModel()); // Output: 'Toyota'
3. Method
A method is a function associated with a class or object. It defines the behavior of the object.
// Method example
class Person {
constructor(name) {
this.name = name;
}
sayHello() {
console.log(`Hello, my name is ${this.name}`);
}
}
const person = new Person('Alice');
person.sayHello(); // Output: 'Hello, my name is Alice'
4. Encapsulation
Encapsulation is the practice of hiding the internal details of an object and exposing only the necessary parts. This is achieved using access modifiers (public, private, protected) in JavaScript.
// Encapsulation example
class BankAccount {
#balance; // Private property
constructor(initialBalance) {
this.#balance = initialBalance;
}
getBalance() {
return this.#balance;
}
deposit(amount) {
this.#balance += amount;
}
}
const account = new BankAccount(1000);
console.log(account.getBalance()); // Output: 1000
account.deposit(500);
console.log(account.getBalance()); // Output: 1500
5. Inheritance
Inheritance is the process of creating a new class from an existing class. The new class inherits properties and methods from the existing class.
// Inheritance example
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} is eating`);
}
}
// Subclass
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
bark() {
console.log(`${this.name} is barking`);
}
}
const dog = new Dog('Buddy', 'Golden Retriever');
dog.eat(); // Output: 'Buddy is eating'
dog.bark(); // Output: 'Buddy is barking'
6. Polymorphism
Polymorphism is the ability of an object to take many forms. In JavaScript, this is achieved by defining methods in a parent class and overriding them in child classes.
// Polymorphism example
class Shape {
area() {
console.log('Calculating area...');
}
}
// Child class
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() {
const result = Math.PI * this.radius * this.radius;
console.log(`Area of circle: ${result}`);
}
}
const shape = new Shape();
shape.area(); // Output: 'Calculating area...'
const circle = new Circle(5);
circle.area(); // Output: 'Area of circle: 78.53981633974483'
Frequently Asked Questions
Q1. What is the difference between a class and an object?
- A class is a blueprint for creating objects, while an object is an instance of a class.
Q2. How do I create a private property in JavaScript?
- In JavaScript, you can create a private property by prefixing the property name with a
#
symbol.
Q3. What is the purpose of the super()
keyword in JavaScript?
- The
super()
keyword is used to call the parent class constructor when creating a subclass.
Q4. Can I inherit from multiple classes in JavaScript?
- JavaScript does not support multiple inheritance directly. However, you can achieve similar functionality using composition or mixins.
Q5. What is the difference between let
, const
, and var
in JavaScript?
let
andconst
are block-scoped, whilevar
is function-scoped.const
is used for variables that do not change, whilelet
is used for variables that do.
Conclusion
Object-Oriented Programming is a powerful paradigm that allows you to create modular, reusable, and maintainable code. By understanding the core concepts of OOP in JavaScript, you can design more efficient and scalable applications. Start by defining classes, creating objects, and utilizing inheritance and polymorphism to build robust applications.