Table of contents
No headings in the article.
What is object-oriented programming?
Object-oriented programming (OOP) is a programming paradigm that is based on the concept of objects.
In OOP, an object is an instance of a class, which is a blueprint that defines the properties and methods of the object. Properties are the characteristics of the object, such as its color, size, or name. Methods are the actions that the object can perform, such as moving, rotating, or resizing.
JavaScript uses prototypes to implement OOP. Prototypes are a way of creating objects that inherit properties and methods from other objects. In JavaScript, every object has a prototype, which is another object that inherits properties and methods.
To create a new object in JavaScript, you can use the object literal notation or the constructor function notation. Here's an example of creating a new object using the object literal notation:
const car = { make: 'Toyota',
model: 'Camry',
year: 2020,
drive :function() {
console.log('Driving...');
}
};
In this example, car
is an object that has the properties make
, model
, and year
, as well as the method drive
.
You can also create objects using constructor functions, which allow you to create multiple objects of the same type:
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.drive
= function() {
console.log('Driving...');
}
}
const car1 = new Car('Toyota', 'Camry', 2020);
const car2 = new Car('Honda', 'Civic', 2021);
In this example, the Car
function is used as a constructor to create two new objects, car1
and car2
. Each object has its own make
, model
, year
, and drive
method.
Overall, OOP in JavaScript allows you to create complex, modular applications by defining objects with their properties and methods and using inheritance to share and reuse code.
It's not enough, here is the movie so let's get deep dive into it:
- Inheritance: Inheritance is a way to create new classes (or objects) that are a modified version of an existing class (or object). In JavaScript, inheritance is implemented using prototypes. A prototype is an object that is used as a template for creating new objects. By setting an object's prototype to another object, you can create a new object that inherits all the properties and methods of the original object. Here's an example:
// Define the parent class
class Animal {
constructor(name) {
this.name
= name;
}
speak() {
console.log(`${
this.name
} makes a noise.`);
}
}
// Define the child class
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${
this.name
} barks.`);
}
}
// Create a new dog object
const myDog = new Dog('Rufus');
// Call the speak method on the dog object
myDog.speak(); // Output: "Rufus barks."
In this example, the Animal
class is the parent class and the Dog
class is the child class that inherits from it. By using the extends
keyword, we tell JavaScript that the Dog
class should inherit from the Animal
class. This allows the Dog
class to use the name
property and speak
method of the Animal
class, and to override the speak
method with its own implementation.
- Encapsulation: Encapsulation is the practice of hiding the internal details of an object from the outside world, and providing a public interface for interacting with the object. This is achieved in JavaScript using closures and the
private
keyword. Here's an example:
class Person {
constructor(name, age)
{
this.name
= name;
let age = age;
this.getAge = function() { return age; }
this.setAge = function(age) {
if (age > 0 && age < 120) {
_age = age;
}
}
}
}
const person = new Person('John', 30);
console.log(
person.name
); // Output: "John"
console.log(person.getAge()); // Output: 30 person.setAge(40); console.log(person.getAge()); // Output: 40 person.setAge(-10);
// This won't have any effect because the age is invalid
console.log(person.getAge()); // Output: 40
In this example, the Person
class has a private _age
variable that is not accessible from outside the class. Instead, the class provides public getAge
and setAge
methods for accessing and modifying the age. This allows us to control access to the internal state of the object, and to ensure that the state is always valid.
- Polymorphism is the ability of an object to take on many forms. In JavaScript, polymorphism can be achieved through method overriding or method overloading.
Method overriding is when a child class provides its own implementation of a method that is already defined in its parent class. The child class can then use this method to perform specific tasks based on its own needs. This allows different objects to respond differently to the same method call.
Here's an example:
class Animal {
makeSound() {
console.log('The animal makes a sound.');
}
}
class Dog extends Animal {
makeSound() {
console.log('The dog barks.');
}
}
class Cat extends Animal {
makeSound() {
console.log('The cat meows.');
}
}
const animal = new Animal();
const dog = new Dog();
const cat = new Cat();
animal.makeSound(); // Output: The animal makes a sound.
dog.makeSound(); // Output: The dog barks.
cat.makeSound(); // Output: The cat meows.
In this example, the Animal
class defines a makeSound
method that prints a generic message. The Dog
and Cat
classes override this method with their own implementations that print specific messages. When the makeSound
method is called on an object of each class, it returns the appropriate message. This is an example of polymorphism through method overriding
- Abstraction: Abstraction is the practice of hiding the implementation details of an object and exposing only the essential features to the outside world. In JavaScript, this is achieved by defining classes and objects with only the necessary properties and methods, and by using access modifiers (such as
private
,public
, andprotected
) to control access to them. Here's an example:
class Car {
constructor(make, model, year)
{
this.make = make;
this.model = model;
this.year = year; }
start() {
console.log('Starting the car...');
}
drive() {
console.log('Driving the car...');
}
stop() {
console.log('Stopping the car...');
}
}
const myCar = new Car('Toyota', 'Camry', 2020);
myCar.start();
myCar.drive
();
myCar.stop();
In this example, the Car
class defines the essential features of a car (the make
, model
, year
, start
, drive
, and stop
methods) and hides the implementation details from the outside world. The myCar
object can be used to start, drive, and stop the car without knowing how these methods are implemented internally. This is an example of abstraction.