ECMAScript 2015, or ES6, introduced JavaScript Classes, which serve as blueprints for creating JavaScript Objects.
Use the class keyword to define a class, and always include a method called constructor().
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 for creating JavaScript objects. |
Once you have a class, you can use it to instantiate objects.
const myCar1 = new Car(“Ford”, 2014); const myCar2 = new Car(“Audi”, 2019); |
The example above uses the Car class to instantiate two Car objects.
The constructor method is automatically invoked when a new object is instantiated. |
The constructor method is a special method that:
The constructor method is a special method that:
class ClassName { constructor() { ... } method_1() { ... } method_2() { ... } method_3() { ... } } |
Define 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 shows the first browser version that fully supports Classes in JavaScript:
Class syntax must be written in “strict mode.” Failure to adhere to “strict mode” rules will result in an error.
In “strict mode,” using a variable without declaring it will result in an error.
class Car { constructor(name, year) { this.name = name; this.year = year; } age() { // date = new Date(); // This will not work const date = new Date(); // This will work return date.getFullYear() – this.year; } } |