Class skeleton
Define a collection class and set up internal state with the constructor.
Constructor and internal state
A class's internal state is the data kept separate for each instance. For Collection that data is an array holding the added items. The constructor special method runs once when an instance is created with new and prepares the internal state.
We'll keep the array in a this.items property. this points to the current instance, so every method reaches the same array. We give it an empty array as the initial value: this.items = [].
What is this?
Inside a class, this represents the running instance. When we write new Collection() a new instance is created; its items property is read as this.items.
Thanks to this, methods reach the same instance's data. If we used an outer variable instead of this, all instances would share the same array and data would get mixed up. That's why we always keep the internal state on this.
Exercise Set up the internal state with the constructor
Add a constructor to the class. Set up the internal state with a this.items property as an empty array.
Show example solution
Write a constructor method with empty parentheses; in the body assign an empty array to this.items.
Example solution:
// Utility library
class Collection {
constructor() {
this.items = [];
}
}
Test yourself
-
When does the constructor run?
- When the class is defined
- When a method is called
- When an instance is created with new
- When exporting
Show answer
When an instance is created with new — Correct! The constructor runs once when an instance is created with new.
-
Set up the internal state as an empty array
this.items = ____;Show answer
this.items = []; -
Match the constructor pieces
- constructor
- setup method
- this
- instance reference
- this.items
- internal array
- []
- empty array