
Updated on 10 January 2023If you are looking for a JavaScript tutorial that covers JavaScript classes, you may be interested in my new JavaScript tutorial.
Defining a class
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
}
To declare a class, use the class keyword followed by the name of the class (Rectangle here).
Constructor: a special method that initialises an instance of the class. Every time we create a new instance, the constructor is invoked.
Methods in a class
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
// Méthode prototype
area() {
return console.log(`La zone est ${this.height*this.width}`);
}
// Méthode statique
static display(rect){
return console.log(`Height: ${rect.height} Width: ${rect.width}`);
}
}
const rectangle = new Rectangle(5, 4); // Instancier la classe
rectangle.area();
// La zone est 20
Rectangle.display(rectangle);
// Height: 5 Width: 4
- Prototype method:
area()is a prototype method. - Static method:
display()is a static method.
Prototype method
A prototype method is a method you can only reach once you have created an instance of the class. As you can see in the example above, the prototype method is called (line 17) on the object, by its name followed by parentheses (any parameters would go inside those parentheses).
Static method
A static method is one you can call without instantiating the class. Static methods are defined on the class itself, not on the object. That means you cannot call a static method on the object (rectangle), only on the class (Rectangle), as shown on line 19.
Inheritance
class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'c\'est ' + this.carname;
}
}
class Model extends Car {
constructor(brand, model) {
super(brand);
this.model = model;
}
show() {
return console.log(`${this.present()} ${this.model}`);
}
}
const mycar = new Model("Ford", "Mustang");
mycar.show();
// c'est Ford Mustang
To set up class inheritance, use the extends keyword.
A class created with class inheritance inherits every method of another class. In the example above, the Model class inherits every method of the Car class.
The super() property refers to the parent class. By calling super() inside the constructor, we call the parent constructor and gain access to the parent properties and methods.
Inheritance is useful for code reuse: you can reuse the properties and methods of an existing class when you create a new one.


