In JavaScript, classes let you define blueprints for creating objects. A class groups related data (properties) and functionality (methods). Think of a class as a template for creating objects.
What is a Class?
A class is a special type of function in JavaScript that helps you organize and reuse code. You use it to define the structure of an object—what properties it has and what methods it can run.
For example, a Car
class might define that every car has a make
, a model
, and a method to display its details.
Declaring a Class
You declare a class using the class
keyword:
class Car {
// Class body goes here
}
By convention, class names start with a capital letter.
Constructor: Setting Up New Objects
The constructor()
is a special method that runs when you create a new instance of a class.
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
}
What’s happening here:
constructor(make, model)
is a function that takes two arguments.this.make = make;
assigns themake
value to the object.this.model = model;
does the same formodel
.
Adding Methods
You can add methods directly inside the class, just like functions:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
displayInfo() {
console.log(`This car is a ${this.make} ${this.model}.`);
}
}
Creating and Using Instances
Now let’s use the Car
class:
const myCar = new Car("Toyota", "Corolla");
console.log(myCar.make); // Output: Toyota
myCar.displayInfo(); // Output: This car is a Toyota Corolla.
Explanation:
new Car(...)
creates a new object from the class.- You can access properties using
myCar.make
. - Call methods like
myCar.displayInfo()
.
Inheritance with extends
Inheritance lets one class reuse the logic of another class using the extends
keyword.
class ElectricCar extends Car {
constructor(make, model, batteryCapacity) {
super(make, model); // Calls the parent (Car) constructor
this.batteryCapacity = batteryCapacity;
}
displayBatteryInfo() {
console.log(`Battery capacity: ${this.batteryCapacity} kWh.`);
}
}
Using super()
When using inheritance, the super()
function calls the parent class’s constructor.
const tesla = new ElectricCar("Tesla", "Model S", 100);
tesla.displayInfo(); // Inherited method
tesla.displayBatteryInfo(); // Own method
Summary
Concept | What It Does |
---|---|
class | Declares a new class |
constructor | Sets up new object properties |
this | Refers to the current object |
new | Creates a new object instance |
Method | Function inside a class |
extends | Inherit from another class |
super() | Calls the parent class’s constructor |