#19 Understanding Object-Oriented Programming in JavaScript
As your apps grow, your code can become messy. Object-Oriented Programming (OOP) is a "style" of coding that helps you organize your data and behavior into neat, reusable packages.
Think of a Class as a blueprint for a house. The blueprint isn't a house itself—it’s just a set of instructions.
When you use that blueprint to actually build a house, you create an Object (also called an Instance). You can use one single blueprint to build 100 different houses, each with its own paint color or furniture, but they all share the same basic structure.
Confuse about object you have learned earlier. Previously Object was the datatype. When we talk about the Object in the OOP. Object is the instance of the class as we have learned above.
Creating a Class in JavaScript
In JavaScript, we use the class keyword to create our blueprint. Inside, we use a special function called a constructor to set up our data.
class Car {
constructor(brand, model) {
this.brand = brand; //"this" refers to the specific car we are building
this.model = model;
}
}
Making an Object (Instantiation)
To "build" a car from our blueprint, we use the new keyword.
const myCar = new Car("Toyota", "Corolla");
const friendCar = new Car("Tesla", "Model 3");
console.log(myCar.brand); // "Toyota"
Adding Methods (Actions)
A class isn't just for storing data. It’s also for defining what an object can do. We call these functions Methods.
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
// This is a Method
drive() {
console.log(`The \({this.color} \){this.brand} is zooming away! 🏎️`);
}
}
const myCar = new Car("Ford", "Red");
myCar.drive(); // Output: The Red Ford is zooming away!
Why Use OOP? (Encapsulation)
One of the main pillars of OOP is Encapsulation. This is a fancy word for "keeping things together."
Instead of having a variable for carColor in one part of your code and a drive() function in another, you wrap them both inside the Car class. This makes your code:
Reusable: You can create 1,000 students or cars with one line of code each.
Organized: You know exactly where to find the logic for a specific "thing."
Practice Assignment
Let’s put the blueprint to work!
Create a Class: Name it
Student.The Constructor: It should accept
nameandgrade.The Method: Create a method called
introducethat logs: "Hi, I'm [name] and I'm in grade [grade]."The Instances: Create two different student objects (e.g.,
student1andstudent2) and call theintroducemethod for both.




