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
classkeyword. - By convention, the class name is capitalized.
- A class has a unique constructor method that is named
constructor. - Think of the
constructorthe same way you thought of them in Java/C++. That is, use them to initialize the state (attributes) of your objects. - In JavaScript, unlike Java/C++, a class can only have one constructor.
- Methods can be declared using a syntax that resembles methods in Java/C++.
- Inside a class declaration, unlike in object literal, method definitions are not separated by a comma.
- Aside: Classes are not hoisted.
A class encapsulates state (data) and behavior (operations). In the example of Note, 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.