
In the previous chapter we looked at how to work with events in JavaScript. This chapter is about classes and objects.
Understanding classes and objects in JavaScript matters, because they let you build more complex data structures and organise your code better. Before getting into them, it helps to know the basics of object-oriented programming.
What is a class in JavaScript?
A class is a blueprint used to create objects. It defines the properties and the methods those objects will have. With classes you can create several objects that share the same properties and methods, which comes in handy in plenty of situations.
Declaring a class
To create a class in JavaScript, use the following syntax:
class MaClasse {
// Class constructor
constructor() {
// Initialise the properties and methods of the class
}
// Class methods
maMethode() {
// Method code
}
}The constructor and the methods of a class
A class definition in JavaScript includes the class constructor, a special method used to create and initialise an object built from that class.
The constructor of a class is defined with the “constructor” keyword. For example:
// Class constructor
constructor() {
// Initialise the properties and methods of the class
}The methods of a class are defined the same way as functions, except that the “function” keyword is not used.
// Class methods
maMethode() {
// Method code
}You reach the methods of an object exactly as you reach its properties, with the following syntax: myObject.myMethod();
const monObjet = new MaClasse();
monObjet.maMethode();Inheritance with classes
Inheritance is a key idea in object-oriented programming (OOP). It means creating a new class from an existing one, inheriting its properties and its methods. That way you reuse code and keep your application easier to organise.
In JavaScript, classes support inheritance through the “extends” syntax. Here is an example of an “Enfant” class inheriting from a “Parent” class:
class Parent {
constructor(nom) {
this.nom = nom;
}
saluer() {
console.log(Bonjour, je suis ${this.nom});
}
}
class Enfant extends Parent {
constructor(nom, age) {
super(nom);
this.age = age;
}
}
const enfant1 = new Enfant('Marie', 7);
enfant1.saluer(); // Bonjour, je suis MarieUsing the super method
The super method is used to call a method of a parent class from a child class. Say you have an Animal class with a “move()” method that defines how animals move, and a Chat class that inherits from Animal: you can use super to call the “move()” method of Animal from the Chat class. Here is an example:
class Animal {
move() {
console.log('Je me déplace');
}
}
class Chat extends Animal {
move() {
console.log('Je me déplace en sautant');
super.move();
}
}
const monChat = new Chat();
monChat.move();
// prints "Je me déplace en sautant" then "Je me déplace"Static methods
Static methods belong to the class itself rather than to its instances. They can be called without instantiating the class. For example, you can define a static “getAnimalType()” method on the Animal class that returns the type of animal. Here is an example:
class Animal {
static getAnimalType() {
return 'Animal';
}
}
console.log(Animal.getAnimalType()); // prints 'Animal'Static methods cannot be called on instances of the class. If you try to call the “getAnimalType()” method on an instance of the Animal class, you get an error.
How do you work with the properties of an object?
You can also pass parameters to the class constructor to initialise the properties of the object:
class MaClasse {
constructor(param1, param2) {
this.param1 = param1;
this.param2 = param2;
}
}
const monObjet = new MaClasse("Valeur de param1", "Valeur de param2");To read a property of an object, use the following syntax:
monObjet.maPropriete;To change a property of an object, use the following syntax:
monObjet.maPropriete = "Nouvelle valeur";To remove a property of an object, use the “delete” operator, like this:
delete monObjet.maPropriete;You cannot delete a property of an object if that property is defined on the object’s prototype. To find out how to deal with inherited properties, see the section on inheritance with objects below.
Adding getters and setters to a class
Getters and setters are methods that let you read and change the properties of an object in a controlled way. They are often used when you want to run some specific logic as a property is read or written.
Here is an example of getters and setters in a class:
class MonObjet {
constructor(propriete) {
this._propriete = propriete;
}
// Getter
get propriete() {
return this._propriete;
}
// Setter
set propriete(value) {
this._propriete = value;
}
}
const objet = new MonObjet('valeur initiale');
console.log(objet.propriete); // prints 'valeur initiale'
objet.propriete = 'nouvelle valeur';
console.log(objet.propriete); // prints 'nouvelle valeur'Getters and setters are methods, not properties. So you have to use the objet.propriete() syntax to read their value, rather than objet.propriete (without parentheses).
In the example above, we used a getter to read the value of the _propriete property, and a setter to change it. We also defined a _propriete property using the this keyword in the class constructor. That property is private and can only be changed through the getter and the setter.
Getters and setters are worth using whenever you need to do something extra as the value of a property is read or written. A setter, for instance, can check that the value passed in is valid before assigning it to the property. Here is an example of getters and setters in a class:
class MonObjet {
constructor(valeur) {
this._maPropriete = valeur;
}
get maPropriete() {
return this._maPropriete;
}
set maPropriete(valeur) {
if (typeof valeur === 'string') {
this._maPropriete = valeur;
} else {
console.log('La valeur doit être une chaîne de caractères');
}
}
}
const monObj = new MonObjet('ma valeur');
console.log(monObj.maPropriete); // Prints 'ma valeur'
monObj.maPropriete = 42; // Prints 'La valeurConclusion
We have seen how to use classes and objects in JavaScript to structure and organise code more effectively, then how to create and work with objects from classes using the constructor and methods. We also covered inheritance with classes, through the super method and static methods. Finally, we looked at getters and setters, which control how the properties of an object are read and written.
In the next chapter we will see how to handle errors and debug our code with try-catch and the debugging tools in the browser. That will help us understand what our code is really doing, and fix it when needed.


