[i]Learn· Using classes
Overview of classes
If you have some hands-on experience with JavaScript, or have followed along with the guide, you probably have already used classes, even if you haven't created one. For example, this may seem familiar to you:
const bigDay = new Date(2019, 6, 19);
console.log(bigDay.toLocaleDateString());
if (bigDay.getTime() < Date.now()) {
console.log("Once upon a time...");
}
On the first line, we created an instance of the class Date, and called it bigDay. On the second line, we called a method toLocaleDateString() on the bigDay instance, which returns a string. Then, we compared two numbers: one returned from the getTime() method, the other directly called from the Date class itself, as Date.now().
Date is a built-in class of JavaScript. From this example, we can get some basic ideas of what classes do:
- Classes create objects through the
newoperator. - Each object has some properties (data or method) added by the class.
- The class stores some properties (data or method) itself, which are usually used to interact with instances.
These correspond to the three key features of classes:
- Constructor;
- Instance methods and instance fields;
- Static methods and static fields.
example 1 of 1
[>_]Terminal
Output appears here when you press Run.
$ ▌