Understanding Object-Oriented Programming (OOP) in JavaScript
Up until now, we’ve used Variables to store data and Functions to perform tasks. But as your apps get bigger, your code can start to look like a messy pile of loose parts.
Object-Oriented Programming (OOP) is a way to organize your code by grouping related data and behaviors into "objects." It’s one of the most powerful skills a developer can have!
The Big Idea: Blueprint vs. Object
The best way to understand OOP is the Blueprint Analogy.
Imagine an architect draws a blueprint for a house. The blueprint isn't a house itself—you can't live in it! However, it contains all the instructions needed to build one. From that one blueprint, you can build ten identical houses, or even change the color of each one.
The Class is the blueprint.
The Object (Instance) is the actual house built from that blueprint.
1. What is a Class?
In JavaScript, a Class is the template we use to create objects. It defines what properties (data) and methods (actions) the object will have.
JavaScript
class Car {
// This is the blueprint for a car
}
2. The constructor Method
The constructor is a special function that runs automatically the moment you create a new object. Its job is to "set up" the initial values of your object.
JavaScript
class Car {
constructor(brand, color) {
this.brand = brand; // "this" refers to the specific car being built
this.color = color;
}
}
3. Creating Objects (Instancing)
To build an object from our class, we use the new keyword.
JavaScript
const car1 = new Car("Tesla", "Red");
const car2 = new Car("BMW", "Blue");
console.log(car1.brand); // Output: Tesla
console.log(car2.brand); // Output: BMW
4. Methods: Adding Behavior
A blueprint doesn't just show what a house looks like; it shows how the doors open. In classes, we add "behaviors" using Methods. A method is simply a function that lives inside a class.
JavaScript
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
// This is a method
drive() {
console.log(this.brand + " is driving away!");
}
}
const myCar = new Car("Toyota", "Silver");
myCar.drive(); // Output: Toyota is driving away!
5. A Basic Idea of Encapsulation
Encapsulation is a fancy word for "bundling." It means keeping the data (properties) and the things that use that data (methods) together in one neat package.
Instead of having a variable carColor and a function paintCar() floating around separately, they both live inside the Car class. This makes your code reusable and much easier to fix if something goes wrong.
🛠 Student Assignment
Let’s build a classroom in code!
The Class: Create a class called
Student.The Properties: Use a
constructorto acceptnameandage.The Method: Add a method called
introducethat prints: "Hi, my name is [name] and I am [age] years old."The Objects: Create two different student objects (e.g.,
student1andstudent2) with different names and ages.The Action: Call the
introducemethod for both students.