ECMAScript 2015 (ES6) introduced JavaScript Classes, which serve as templates for creating JavaScript objects.
Use the class keyword to define a class, and always include a constructor() method.
class ClassName { constructor() { ... } } |
class Car { constructor(name, year) { this.name = name; this.year = year; } } |
The example above defines a class called “Car,” which has two initial properties: “name” and “year.”
A JavaScript class is not an object; it is a blueprint or template for creating JavaScript objects. |
Once you have a class, you can use it to create objects.
const myCar1 = new Car(“Ford”, 2014); const myCar2 = new Car(“Audi”, 2019); |
The example above uses the Car class to create two instances of the Car object.
The constructor method is called automatically when a new object is instantiated. |
The constructor
method is a special method that:
Class methods are defined using the same syntax as object methods.
To create a class, use the class keyword.
Always include a constructor() method.
After that, you can add any number of methods to the class.
class ClassName { constructor() { ... } method_1() { ... } method_2() { ... } method_3() { ... } } |
Create a class method called age
that returns the age of the car.
class Car { constructor(name, year) { this.name = name; this.year = year; } age() { const date = new Date(); return date.getFullYear() – this.year; } } const myCar = new Car(“Ford”, 2014); document.getElementById(“demo”).innerHTML = “My car is “ + myCar.age() + ” years old.”; |
You can pass parameters to class methods.
class Car { constructor(name, year) { this.name = name; this.year = year; } age(x) { return x – this.year; } } const date = new Date(); let year = date.getFullYear(); const myCar = new Car(“Ford”, 2014); document.getElementById(“demo”).innerHTML= “My car is “ + myCar.age(year) + ” years old.”; |
The following table lists the first browser version that fully supports classes in JavaScript.
You will learn much more about JavaScript classes later in this tutorial. |