What is Object-Oriented Programming
Object-oriented programming (OOP) is a programming paradigm that is widely used in software development. In OOP, code is organized around objects, which contain both data and behavior. These objects are instances of classes, which serve as blueprints for creating them. In this article we will learn about JavaScript Object-Oriented Programming
JavaScript Object-Oriented Programming
JavaScript is a versatile language that supports several programming paradigms, including object-oriented programming (OOP). OOP in JavaScript involves the use of objects, which are collections of data and functions that can interact with each other.
Objects
In JavaScript Object-Oriented Programming, an object is a collection of properties and methods that represent a real-world entity or concept. Here is an example of how to create and use an object in JavaScript:
// Define an object using object literal syntax
const car = {
make: 'Toyota',
model: 'Corolla',
year: 2022,
drive: function() {
console.log(`The ${this.make} ${this.model} is driving...`);
}
};
// Access object properties
console.log(car.make); // Output: Toyota
console.log(car.year); // Output: 2022
// Call object method
car.drive(); // Output: The Toyota Corolla is driving...
In this example, we define an object called car using object literal syntax. The object has properties such as make, model, and year, as well as a method called drive. The drive method uses the this keyword to reference the object’s own properties.
We can then access the object’s properties using dot notation (car.make) and call the object’s method (car.drive()). The output of calling the drive method is a console log message that indicates the make and model of the car that is driving.
Overall, objects are a fundamental aspect of JavaScript OOP and are used extensively to represent real-world entities or concepts in code. By defining objects with properties and methods, we can encapsulate data and behavior and create more modular and reusable code.
Constructor Function
In JavaScript, constructor functions are used to create new objects based on a defined template or class. Constructor functions allow us to define the properties and methods of an object, as well as initialize its state. Here is an example of how to create and use a constructor function in JavaScript:
// Define a constructor function for a Car class
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.drive = function() {
console.log(`The ${this.make} ${this.model} is driving...`);
};
}
// Create new Car objects using the constructor function
const car1 = new Car('Toyota', 'Corolla', 2022);
const car2 = new Car('Honda', 'Civic', 2023);
// Access object properties
console.log(car1.make); // Output: Toyota
console.log(car2.year); // Output: 2023
// Call object method
car1.drive(); // Output: The Toyota Corolla is driving...
In this example, we define a constructor function called Car that takes in three parameters: make, model, and year. Inside the constructor function, we use the this keyword to set the values of the object’s properties and define its drive method.
We can then create new Car objects using the new keyword and passing in the appropriate parameters. The resulting objects will have their own set of properties and methods based on the values passed to the constructor function.
We can access the properties of each Car object using dot notation (car1.make, car2.year) and call their drive method (car1.drive()). The output of calling the drive method is a console log message that indicates the make and model of the car that is driving.
Prototypes
These are a mechanism for sharing properties and methods among objects of the same class in JavaScript Object-Oriented Programming. When we define a constructor function, we can also define a prototype object that will be used as a template for all objects created from that constructor. Here is an example of how to use prototypes in JavaScript:
// Define a constructor function for a Person class
function Person(name, age) {
this.name = name;
this.age = age;
}
// Add a method to the Person prototype
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
// Create new Person objects using the constructor function
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
// Call object method using the prototype
person1.sayHello(); // Output: Hello, my name is Alice and I am 30 years old.
// Check if an object has a property defined in its prototype
console.log(person2.hasOwnProperty('name')); // Output: true
console.log(person2.hasOwnProperty('sayHello')); // Output: false
We define a constructor function called Person that takes in two parameters: name and age. Then we define a method called sayHello on the Person prototype using dot notation and a function expression.
After this, we create new Person objects using the constructor function and call their sayHello method using dot notation and the prototype. The output of calling the sayHello method is a console log message that includes the object’s name and age properties.
We can also use the hasOwnProperty method to check if an object has a particular property defined in its own properties or in its prototype.
In this example, we see that person2 has its own name property but not its own sayHello method, which is instead defined in the Person prototype.
Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows a class to inherit properties and methods from another class. In JavaScript, we can implement inheritance using the prototype object.
Here is an example of inheritance in JavaScript:
// Define the parent class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
// Define the child class that inherits from Animal
class Dog extends Animal {
speak() {
console.log(`${this.name} barks.`);
}
}
// Create an instance of the Dog class
const d = new Dog('Fido');
// Call the speak() method on the instance
d.speak(); // Output: "Fido barks."
In this example, the Dog class extends the Animal class using the extends keyword. This means that the Dog class inherits the name property and speak() method from the Animal class.
The speak() method is overridden in the Dog class to provide a custom implementation. When the speak() method is called on an instance of the Dog class, the custom implementation in the Dog class is executed.
Inheritance allows us to create a hierarchy of related classes that share common functionality. It helps to reduce code duplication and makes our code more modular and easier to maintain.
Encapsulation
In JavaScript Object-Oriented Programming , encapsulation is a fundamental concept in Object-Oriented Programming (OOP) that refers to the idea of bundling data and functions that operate on that data within a single unit called a class. In JavaScript, we can achieve encapsulation using classes.
Encapsulation helps to protect the data from being accessed or modified from outside the class. It ensures that the data can only be accessed or modified through specific methods or functions that are defined within the class.
Here’s an example of encapsulation in JavaScript:
class Car {
constructor(make, model, year) {
this._make = make;
this._model = model;
this._year = year;
}
get make() {
return this._make;
}
set make(make) {
this._make = make;
}
get model() {
return this._model;
}
set model(model) {
this._model = model;
}
get year() {
return this._year;
}
set year(year) {
this._year = year;
}
start() {
console.log(`${this._make} ${this._model} (${this._year}) is starting...`);
}
stop() {
console.log(`${this._make} ${this._model} (${this._year}) is stopping...`);
}
}
const myCar = new Car('Toyota', 'Corolla', 2022);
myCar.start();
myCar.stop();
console.log(myCar.make); // Output: Toyota
myCar.make = 'Honda';
console.log(myCar.make); // Output: Honda
In the above example, we have defined a Car class with three properties: _make, _model, and _year. These properties are marked as private by using an underscore prefix. We have also defined getter and setter methods for these properties. This ensures that the properties can only be accessed or modified through these methods.
The start() and stop() methods are defined within the class, which operate on the properties of the class. When we create an instance of the Car class and call the start() and stop() methods, it will output the appropriate messages.
Finally, we create an instance of the Car class and use the getter and setter methods to access and modify the _make property. This demonstrates how encapsulation protects the data from being accessed or modified from outside the class, ensuring that it can only be accessed or modified through specific methods or functions that are defined within the class.
Polymorphism
Polymorphism in JavaScript is the ability of an object to take on multiple forms. It allows different objects to implement the same method or property in different ways. This is achieved through method overloading or overriding.
Method overloading is when multiple methods have the same name but different parameters. When a method is called, the appropriate version of the method is executed based on the number and type of the parameters passed.
Method overriding is when a subclass provides its own implementation of a method that is already defined in the parent class. When the method is called on an object of the subclass, the overridden method is executed instead of the parent method.
Here’s an example of method overriding in JavaScript:
class Animal {
makeSound() {
console.log("The animal makes a sound");
}
}
class Dog extends Animal {
makeSound() {
console.log("The dog barks");
}
}
let animal = new Animal();
let dog = new Dog();
animal.makeSound(); // Output: The animal makes a sound
dog.makeSound(); // Output: The dog barks
In this example, we have an Animal class with a makeSound method that simply logs a message to the console. We then create a Dog class that extends Animal and overrides the makeSound method to log a message that the dog barks.
When we create an instance of Animal and call the makeSound method, it logs the message for the Animal class. However, when we create an instance of Dog and call the makeSound method, it logs the message for the Dog class, because the Dog class has overridden the makeSound method of the Animal class.
Abstraction
Abstraction in JavaScript OOP is the process of hiding the complexity of the implementation and only showing the essential features to the user. In JavaScript, we can achieve abstraction through the use of classes and interfaces.
For example, let’s consider a class named Shape which has a method getArea(). We can create subclasses such as Rectangle and Circle which inherit from the Shape class and implement their own versions of getArea(). By doing so, we can abstract away the details of how getArea() is calculated for each shape.
Here is an example code snippet:
class Shape {
getArea() {
// abstract method, to be implemented by subclasses
}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
getArea() {
return Math.PI * this.radius ** 2;
}
}
In this example, the Shape class serves as an abstraction for calculating the area of various shapes. The Rectangle and Circle classes inherit from the Shape class and implement their own version of getArea(), which is specific to their shape.
By using abstraction, we can simplify the code for the user by hiding the details of how the getArea() method is implemented for each shape.
Conclusion of JavaScript Object-Oriented Programming
To summarize, Object-Oriented Programming (OOP) is a programming paradigm that organizes code around objects, which contain both data and behavior. In JavaScript OOP, an object is a collection of properties and methods that represent a real-world entity or concept. JavaScript supports the use of constructor functions to create new objects based on a defined template or class. Prototypes are used to share properties and methods among objects of the same class, while inheritance allows a class to inherit properties and methods from another class. Overall, the use of objects and OOP concepts in JavaScript allows for more modular and reusable code.
You would also like to explore 10 Hidden javaScript Concepts