CodePark/ questions / Prototypes & classes
START PRACTICINGPRACTICE
Frontend question · JavaScript › Prototypes & classes

ES6 classes are often called syntactic sugar. What does that mean, and are they only sugar?

"Syntactic sugar" means a nicer way to write something that already exists. A class is mostly that: it still uses constructor functions and prototypes underneath. But it also adds real behaviour, so it is not only sugar.

What is the same as prototypes:

  • class Dog extends Animal {} creates a constructor function. typeof Dog is 'function'.
  • Methods go on Dog.prototype.
  • extends links Dog.prototype to Animal.prototype. It also links Dog itself to Animal, so static methods are inherited.
  • There is no separate class-based object model.

What is different from constructor functions:

  • Calling a class without new throws an error.
  • Class bodies are always in strict mode.
  • Methods are non-enumerable, so they do not show up in for...in loops.
  • A class declaration is in the temporal dead zone (TDZ) until its line runs, so you cannot use it earlier.
  • In a derived class, you must call super() before you use this.

Classes also offer features that are hard to build by hand. Examples are truly private #fields and static initialization blocks.

  • Classes are built on constructor functions and prototypes.
  • Methods live on Class.prototype, and extends sets up the prototype chain.
  • A class must be called with new. Its body is strict and its methods are non-enumerable.
  • In a derived constructor, you must call super() before using this.
  • Private #fields are a truly new feature, not just sugar.