Skip to content

Instantly share code, notes, and snippets.

@rauschma
Last active April 8, 2018 02:26
Show Gist options
  • Save rauschma/e99867645b5f1a0cc42f to your computer and use it in GitHub Desktop.
Save rauschma/e99867645b5f1a0cc42f to your computer and use it in GitHub Desktop.

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 super.

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 (window in browsers), class declarations don’t (they are still seen in all nested scopes, though).
@ReneKriest
Copy link

Forward reference: Function declarations can, while func expressions/classes cannot.

@rauschma
Copy link
Author

@ReneKriest: I’ve edited the Gist to mention that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment