JavaScript classes, introduced in ES6, are syntactical sugar over JavaScript prototype-based inheritance. Classes are in fact "special functions". You can define classes in JavaScript using the class keyword using the following syntax −
class Person {
// Constructor for this class
constructor(name) {
this.name = name;
}
// an instance method on this class
displayName() {
console.log(this.name)
}
}This is essentially equivalent to the following declaration −
let Person = function(name) {
this.name = name;
}
Person.prototype.displayName = function() {
console.log(this.name)
}This class can also be written as a class expressions. The above format is a class declaration. The following format is a class expression −
// Unnamed expression
let Person = class {
// Constructor for this class
constructor(name) {
this.name = name;
}
// an instance method on this class
displayName() {
console.log(this.name)
}
}No matter how you define the classes as mentioned above, you can create objects of these classes using the following −
Example
let John = new Person("John");
John.displayName();Output
John
You can read in depth about JS classes and the class keyword at https://www.tutorialspoint.com/es6/es6_classes.htm.