Class Syntax

We use the class construct to define a type and create encapsulation.

class Note {
  constructor(content) {
    this.text = content;
  }

  print() {
    console.log(this.text);
  }
}
  • A class is declared using the class keyword.
  • By convention, the class name is capitalized.
  • A class has a special constructor method that is named constructor.
  • Think of the constructor the same way you thought of them in Java/C++. That is, use them to initialize the state (attributes) of your objects.
  • Unlike Java/C++, in JavaScript, a class can only have one constructor.
  • Methods can be declared using a syntax that resembles methods in Java/C++.
  • Inside a class declaration, there are no commas between method definitions.
  • Aside: Classes are not hoisted.

A class encapsulates state (data) and behavior (operations). In the example of Page, the data is a string of text stored in a this.text member property. The behavior is print(), a method that dumps the text to the console.