JavaScript Classes
JavaScript Classes are templates for creating objects. They encapsulate data with code to work on that data.
Class Syntax
Use the keyword class to create a class. Always add a method named constructor():
javascript
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
let myCar = new Car("Ford", 2014);
console.log("My car is " + myCar.age() + " years old.");Test Yourself with an Exercise
What is the name of the special method for creating and initializing an object created with a class?