React ES6 Classes

Introduction to ES6

ES6, also known as ECMAScript 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.




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:

class Animal {
  constructor(species) {
    this.species = species;
  }
}

Notice that the class name “Car” 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.

const myPet = new Animal("Dog");




Adding Methods

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

class Animal {
  constructor(species) {
    this.species = species;
  }
  
  describe() {
    return `This is a ${this.species}`;
  }
}

const myPet = new Animal("Dog");
console.log(myPet.describe());




Class Inheritance

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

class Animal {
  constructor(species) {
    this.species = species;
  }

  describe() {
    return `This is a ${this.species}`;
  }
}

class Breed extends Animal {
  constructor(species, breed) {
    super(species);
    this.breed = breed;
  }  
  details() {
    return `${this.describe()}, it is a ${this.breed}`;
  }
}

const myPet = new Breed("Dog", "Golden Retriever");
console.log(myPet.details());

Scroll to Top