In this lesson, you will learn how JavaScript classes improve the language.
Constructor functions
We often need to create many objects of the same kind, like users or cars. In object-oriented languages, a class is often used for this purpose. JavaScript, being a prototype-based language, has something called constructor functions.
// ES5 constructor function
function Car(brand) {
this.brand = brand;
}
// Adding a method to the prototype
Car.prototype.getBrand = function() {
return this.brand;
}
Classes, introduced with ES6, provide “syntactical sugar,” which is comparable to inheritance in object-oriented languages. Classes are special functions meant to mimic the class
keyword from these other languages.
Defining a class
To define a class, we use the class
keyword followed by the name of the class. The body of a class is the part that is enclosed in curly braces {}
:
class Car {
// Body of the class
}
The code above defines a class named Car. This syntax is named class declaration.
The new
operator instantiates the class:
const myCar = new Car();
This is how we create a new object, an instance, of the Car class.
console.log(typeof Car); // -> function
As you can see, a class is a kind of function in JavaScript.
We don’t need to give the class a name. By using a ...