React ES6 Classes

Introduction to ES6

ES6, also known as ECMAScript6 published in 2015, is a significant update to JavaScript that introduced many features for writing more efficient and maintainable code. Some of the notable features include arrow functions, template literals, destructuring assignments, and importantly, classes.

Tutorials dojo strip

What are Classes?

With ES6, the concept of classes was introduced. A class is essentially a type of function, but instead of the function keyword, the class keyword is used. The class properties are defined within a constructor() method.

Basic Class Structure

Here is a simple example to illustrate a class constructor:

JavaScript

Notice that the class name “Animal” starts with an uppercase letter, which follows the standard naming convention for classes.

Now, you can create objects using this class:

The constructor() method is automatically invoked when an object is instantiated.

JavaScript

Adding Methods

Methods can be added to a class to extend its functionality. In this example, describe() is a method of the Animal class, and it is called by referring to the object’s method name followed by parentheses (any parameters would go inside the parentheses):

JavaScript

Class Inheritance

Classes can inherit properties and methods from another class using the extends keyword. In this example, the Breed class inherits from the Animal class. The super keyword is used to call the constructor of the parent class within the child class’s constructor:

JavaScript

Tutorials dojo strip