JavaScript offers many programming paradigms, and object-oriented programming is one of them. Everything in JavaScript is an object including functions. Modern JavaScript also added support for Classes.
In the last article, we have learned about template strings. Let’s see the class now.
Class is a template or a blueprint, for you to define shared structure and behavior between similar objects.
You can define new classes, make them extend to other classes, and instantiate objects out of them using the new keyword.
You can customize the construction of every object and define shared functions between these objects.
Here is the standard class example to demonstrate all these features.
JavaScript Class Example
class Employee { constructor(name) { this.name = name; } greet() { console.log(`Hello ${this.name}!`) } } class Teacher extends Employee { constructor(name, level) { super(name); this.level = level; } greet() { console.log(`Hello ${this.name}! from ${this.level}`) } } const obj1 = new Employee('Julia'); const obj2 = new Teacher('Max','Primary'); const obj3 = new Teacher('Jane', 'Secondary'); obj3.greet = () => console.log('Hey I am Extraordinary'); obj1.greet(); obj2.greet(); obj3.greet();
We have an Employee class and Teacher class that extends Employee class. Every Teacher is also an Employee. Both classes define a constructor function.
A constructor is a special function that gets called every time when we instantiate/initialize an object of the class.
We do instantiate/initialize using ‘new‘ keyword. See in the above example how we have done initialization for one object of Employee and two objects Teacher.
Arguments we have passed when we instantiate these objects are accessible to a constructor.
Employee class expects name argument and stores that into the instance using this keyword.
Teacher class expect the name and level arguments. It stores the value of level on its instance and since it extends Employee class it calls its constructor by using the super method to store the value of a name.
Both classes define greet function that uses the values they store on each instance.
In the third (obj3) object, which we instantiate from the Teacher class. We also have defined greet function directly on an object.
obj1 will use greet function from Employee class and display ‘Hello Julia‘.
obj2 will use greet function from Teacher class and display ‘Hello Max! from Primary‘.
obj3 will override greet method from Teacher class because it has a self-defined method. It will display, ‘Hey I am Extraordinary‘.
See output here in console window.
This is how we define JavaScript Classes. In the upcoming article, we will explore the last topic of JavaScript for React tutorial.