JavaScript Classes
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().
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.
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.
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.
Summary
- Classes are a template for creating objects.
- The
constructormethod is called automatically when a new object is created. extendsis 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?
Enjoying these tutorials?