How are classes different from traditional functions?
ES6 introduced a new protocol for constructing instances, but its features (incl.
new.target) work in both classes and traditional functions. These are the differences between traditional functions and classes:
Traditional functions can’t make superconstructor calls via
super(). That means that they are always base classes. In ES5, superconstructors are called as functions.
The prototype of traditional functions and base classes is
Function.prototype. The prototype of a derived class is its superclass.
Classes can’t be function-called. An exception is thrown if you do.
Additionally, method definitions (in either class definitions or object literals) create functions that are different from traditional functions:
- Methods can’t be constructor-called.
- Each method has the internal property
[[HomeObject]]that points to the object in which the method is stored. That property enables superproperty access (
super.prop). Traditional functions are not allowed to use
The differences between class declarations and function declarations are interesting, too:
- Function declarations are hoisted, class declarations aren’t.
- Class declarations have inner names (like named function expressions), function declarations don’t.
- Function declarations create properties for the global object (
windowin browsers), class declarations don’t (they are still seen in all nested scopes, though).