We use the class construct in JavaScript to define a type and create encapsulation.
class
keyword.constructor
, even if one isn’t explicitly provided.constructor
is used to create objects. It’s typically used to initialize the state or attributes of your objects, much like in Java/C++.A class encapsulates state (data) and behavior (operations). For instance, in the Note
class, the data is a string of text stored in the this.text
member property. The behavior is print()
, a method that outputs the text to the console.
this
keywordYou must use the keyword this
within a method of a class to define or access class properties.
If you modify the display
function in the following way, an error will occur.
In this incorrect usage, the make
and model
properties are being referenced without the this
keyword. This results in a ReferenceError, as make
and model
are not defined within the scope of the display
method.
A class needs to be instantiated (using the new
keyword) once or more to create objects for use within the program.
The snippet below demonstrates how to create an instance of the Note
class. Note that we don’t call Note.constructor()
. Instead, we use the new
keyword followed by the class name.
Observe that typeof Note
specifies that Note
is a function! JavaScript’s class is mostly syntactic sugar. Under the hood, it uses object constructor functions and prototype chains to generate objects.
Here’s something to note: while classes are indeed functions, they are not hoisted. This means you must declare a class before using it.
The dot notation, which is likely familiar to you, is used to access a property or invoke a method on an object instantiated from a class.
Class declarations can be used in expressions!
You cannot use Person
as a class (constructor function). Instead, you must use Student
. The class name can be omitted to create an anonymous class in a class expression.