JavaScript Classes
A class is a blueprint for creating objects with shared properties and methods. The class states what each object holds, and the new keyword builds one object from it.
Define a class
The class keyword starts the blueprint. The constructor sets the starting values for each new object.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}Create an instance
new runs the constructor and returns the new object. Its properties hold the values passed in.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const car = new Car("Ford", 2020);
console.log(car.name, car.year);Add a method
A method uses the values stored on the instance. This one works out the age of the car.
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(currentYear) {
return currentYear - this.year;
}
}
const car = new Car("Ford", 2020);
console.log(car.age(2026));Example
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age(currentYear) {
return currentYear - this.year;
}
}
const first = new Car("Ford", 2020);
const second = new Car("Honda", 2018);
console.log(first.name);
console.log(second.name);
console.log(first.age(2026));Key points
- A class is not an object.
- The new keyword creates an object from a class.
- An object created from a class is called an instance of the class.
- The constructor is a special method that runs when an instance is created.
- The constructor stores starting values on the instance through this.
- Each instance holds its own values, separate from other instances.
- A method is a function defined inside the class body.
In this example, two instances are created from the one Car class. Each instance keeps its own name and year. Calling age on the first instance returns 6.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does the new keyword do with a class?