Modern JavaScript for React: Classes – Part 6

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.

Modern JavaScript for React - 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 behaviour 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 customise 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

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.

Tutorial Funda

Tutorial Funda will keep you updated with the latest Programming Languages, Software Tools and related technologies used in Software Development.

Leave a Reply

Your email address will not be published. Required fields are marked *