Object-Oriented Programming (OOP) is a programming paradigm that uses objects to design and structure software. JavaScript supports OOP concepts, which include classes, objects, inheritance, encapsulation, and polymorphism. Let's dive into each of these concepts with examples.
Classes and Objects
Class Definition
A class in JavaScript is like a blueprint for creating objects. You define properties and methods within a class.
javascript
classPerson{
constructor(name, age) {
this.name= name;
this.age= age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Creating an objectconstjohn = newPerson('John', 30);
john.greet(); // Output: Hello, my name is John and I am 30 years old.
Inheritance
Inheritance allows one class to inherit properties and methods from another class. The extends keyword is used to create a subclass.
javascript
classEmployeeextendsPerson{
constructor(name, age, jobTitle) {
super(name, age); // Call the parent class constructorthis.jobTitle= jobTitle;
}
displayJob() {
console.log(`I am a ${this.jobTitle}.`);
}
}
constjane = newEmployee('Jane', 25, 'Software Engineer');
jane.greet(); // Output: Hello, my name is Jane and I am 25 years old.jane.displayJob(); // Output: I am a Software Engineer.
Encapsulation
Encapsulation is the concept of restricting access to certain properties or methods of an object. In JavaScript, this can be achieved using private fields (prefixed with #) or closures.
Polymorphism allows objects of different classes to be treated as objects of a common super class. In JavaScript, polymorphism can be achieved through method overriding.
javascript
classAnimal{
speak() {
console.log('Animal makes a sound');
}
}
classDogextendsAnimal{
speak() {
console.log('Dog barks');
}
}
classCatextendsAnimal{
speak() {
console.log('Cat meows');
}
}
constanimals = [newAnimal(), newDog(), newCat()];
animals.forEach(animal =>animal.speak());
// Output:// Animal makes a sound// Dog barks// Cat meows
These are the fundamental concepts of OOP in JavaScript. With these concepts, you can create more organized, modular, and maintainable code. Let me know if you'd like to explore any of these topics further