JavaScript Classes Review
Lesson Overview
In this review, we will cover the core concepts of Object-Oriented Programming (OOP) in JavaScript, focusing on the modern `class` syntax and how it relates to JavaScript's prototype-based system.
In this review, we will cover the core concepts of Object-Oriented Programming (OOP) in JavaScript, focusing on the modern class syntax and how it relates to JavaScript’s prototype-based system.
1. Classes as Blueprints
A class serves as a template for creating objects. It defines the properties and behaviors that the objects created from it (instances) will have.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
displayInfo() {
console.log(`Car: ${this.make} ${this.model}`);
}
}
2. The constructor Method
The constructor is a special method used for creating and initializing an object created with a class. It runs automatically when you use the new keyword.
3. The this Keyword
Inside a class, this refers to the specific instance of the object being created or manipulated. It allows you to set and access properties unique to each object.
4. Inheritance with extends and super
Inheritance allows a class to adopt the properties and methods of another class. This promotes code reuse and organizational clarity.
extends: Used to create a child class.super: Used inside the child’s constructor to call the parent’s constructor.
class ElectricCar extends Car {
constructor(make, model, batteryCapacity) {
super(make, model); // Calls the parent constructor
this.batteryCapacity = batteryCapacity;
}
}
5. Prototypes: Under the Hood
It’s important to remember that JavaScript classes are “syntactic sugar” over JavaScript’s existing prototype-based inheritance. Even when using the class keyword, JavaScript is still using prototypes behind the scenes to link objects and share methods.
Summary
- Classes: Templates for objects.
- Constructor: Initialization function.
this: Reference to the current instance.- Inheritance: Sharing behavior between classes using
extends. - Prototypes: The underlying mechanism for inheritance in JavaScript.