JavaScript Classes are templates for JavaScript Objects. Introduced in ES6 (2015), they provide a much cleaner and more structured way to create objects and deal with inheritance than the older prototype-based approach.
Use the keyword class to create a class. Always add a method
named constructor():
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
The constructor method is special—it is executed automatically
when a new object is created.
Use the new keyword to create an object from the class template.
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
You can add methods to your classes just like you would with objects. Methods are shared across all instances of the class.
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.");
"use strict"; directive.
constructor() method is where you initialize
propertiesnew keyword to create an instance