Web Analytics

JavaScript Classes

Advanced ~20 min read

Introduction to Classes

ES6 introduced JavaScript Classes. Classes are templates for creating objects. They encapsulate data with code to work on that data.

Note: JavaScript classes are built on prototypes but provide a cleaner syntax.

Class Syntax

Use the class keyword to create a class. Always add a method named constructor().

HTML
CSS
JS

Class Inheritance

To create a class inheritance, use the extends keyword. A class created with a class inheritance inherits all the methods from another class.

The super() method refers to the parent class. By calling the super() method in the constructor method, we call the parent's constructor method and get access to the parent's properties and methods.

HTML
CSS
JS

Getters and Setters

Classes also allow you to use getters and setters. It can be smart to use getters and setters for your properties, especially if you want to do something special with the value before returning them, or before you set them.

HTML
CSS
JS

Static Methods

Static methods are defined on the class itself, not on the instance of the class. You cannot call a static method on an object, only on the class.

HTML
CSS
JS

Summary

  • Classes are a template for creating objects.
  • The constructor method is called automatically when a new object is created.
  • extends is used for inheritance.
  • super() calls the parent constructor.
  • Static methods belong to the class, not the instance.

Quick Quiz

Which keyword is used to create a class inheritance?

A
inherits
B
extends
C
super
D
implements