Object-Oriented Programming in JavaScript
Object Oriented Programming(OOP) in JavaScript is a programming style that uses classes and objects. Classes are blueprints to make objects while objects are specimens of a class that represents a real world entity.
Eg. A class in JavaScript would resemble an umbrella term car, while a particular car suppose Defender is an object of car class.
JavaScript Classes:
JavaScript classes are blueprints used to create objects. It is a cleaner way to implement object oriented programming. Classes have constructor method to automatically execute when a new object is created using the new keyword. It is used to create and initialise functions. It creates multiple objects with same properties and methods.
JavaScript Objects:
An object in JavaScript is a specimen of class that represents a real world entity. It has its own properties and can access methods that have been defined in its class.
Properties -> data about the object
Methods-> actions that object can perform
Eg. class Car {
constructor (brand, model){
this.brand = brand;
this.model = model;
};
details() {
console.log(`This car is a \({this.brand} \){this.model}.` );
} };
//creating objects from class
const car1 = new Car ("Toyota", "Corolla");
const car2 = new Car ("Mercedes", "G Wagon");
//using objects
car1.details(); // output: This car is a Toyota Corolla
car2.details(); // output: This car is Mercedes G Wagon
Why OOP is needed?
Before OOP:
Changing in one team's code caused other codes to break.
Limited code reusability.
Difficult maintenance of large code base.
After OOP:
Code becomes organised.
Code becomes reusable.
Large problems get managed.
OOP solved these problems by combining data into a single unit called an object.
This is done through:
Encapsulation: Combining data and functions into a common object.
Inheritance: Enables child class to inherit properties from a parent, promoting code reuse.
Polymorphism: Objects can take multiple forms using same interface.
Abstraction: Complex implementation details are hidden, and only essential features are exposed to the user.
These methods allow developers to write cleaner code and write real world scenarios effectively.
Assignment
class Student {
constructor (name, age){
this.name= name;
this.age = age;
}
details(){
console.log("name: " + this.name);
console.log("age:" + this.age);
}};
let s1 = new Student("Ansh", 23);
let s2 = new Student("Sid", 22);
s1.details();
s2.details();