13. Classes in ES6

ES6 introduces new class syntax. One thing to note here is that ES6 class is not a new object-oriented inheritance model. They just serve as a syntactical sugar over JavaScript’s existing prototype-based inheritance.

One way to look at a class in ES6 is just a new syntax to work with prototypes and contructor functions that we’d use in ES5.

Functions defined using the static keyword implement static/class functions on the class.

  1. class Task {
  2. constructor() {
  3. console.log("task instantiated!");
  4. }
  5. showId() {
  6. console.log(23);
  7. }
  8. static loadAll() {
  9. console.log("Loading all tasks..");
  10. }
  11. }
  12. console.log(typeof Task); // function
  13. const task = new Task(); // "task instantiated!"
  14. task.showId(); // 23
  15. Task.loadAll(); // "Loading all tasks.."

extends and super in classes

Consider the following code:

  1. class Car {
  2. constructor() {
  3. console.log("Creating a new car");
  4. }
  5. }
  6. class Porsche extends Car {
  7. constructor() {
  8. super();
  9. console.log("Creating Porsche");
  10. }
  11. }
  12. let c = new Porsche();
  13. // Creating a new car
  14. // Creating Porsche

extends allow child class to inherit from parent class in ES6. It is important to note that the derived constructor must call super().

Also, you can call parent class’s method in child class’s methods using super.parentMethodName()

Read more about classes here

A few things to keep in mind:

  • Class declarations are not hoisted. You first need to declare your class and then access it, otherwise ReferenceError will be thrown.
  • There is no need to use function keyword when defining functions inside a class definition.