JavaScript has been a prototypal based language using object prototypes to create object inheritance and code reuse.
The new ES6 Class adds a new syntax on top of traditional prototypes.
The class syntax has two components: class expressions and class declarations.
Class declarations
One way to define a class is using a class declaration. To declare a class, you use the class keyword with the name of the class ("Person" here).
Class expressions
A class expression is another way to define a class. Class expressions can be named or unnamed. The name given to a named class expression is local to the class's body.
Constructor
The constructor method is a special method for creating and initializing an object created with a class.
There can only be one special method with the name "constructor" in a class.
A SyntaxError
will be thrown if the class contains more than one occurrence of a constructor method.
A constructor can use the super keyword to call the constructor of a parent class.
Hoisting
An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. You first need to declare your class and then access it, otherwise code like the following will throw a ReferenceError
:
Static methods
The static keyword defines a static method for a class. Static methods are called without instantiating their class and are also not callable when the class is instantiated.
Static methods are often used to create utility functions for an application.
Inheritance
The extends keyword is used in class declarations or class expressions to create a class as a child of another class.
ES6 introduced two keywords extends
and super
to inherit properties and methods from parent class.
The extends
keyword is used in class declarations or class expressions to create a class as a child of another class.
The super
keyword is used to call functions on an object's parent.