Book
Submodule 13.2: JavaScript classes
Submodule 13.2: JavaScript classes
Completion requirements
View
- Introduction to JavaScript classes
- The syntax of JavaScript classes
- Create objects with JavaScript classes
- Methods inside JavaScript classes
Create objects with JavaScript classes
In the previous chapter, we saw the syntax to define a class.
In order to actually create objects, we have to call the class. This is done in similar way with what we show on "Submodule 6.3: Constructor functions". We use the new keyword followed by a call to the class name.
For example, in order to create an object for the class we created in the previous chapter:
class Dishes {
constructor(category, price) {
this.category = category;
this.price = price;
}
}
we will write:
let dish1;
dish1 = new Dishes ("sweets", 5);
Using the above syntax, we can create as many new objects as we want. They will all have the properties defined inside their class.
What do you think will be the output of the console if you type dish1;? To find the answer, go to your console and copy/paste both the class and the new object created.
The output will be:
Dishes {category: "sweets", price: 5}