constructor and this
JavaScript · Unit 12: Classes and objects
- Full plan
- JavaScript
- 10 exercises
Setting each property after new is easy to forget. The constructor is a function inside the class that runs by itself on every new: it receives the data and stores it in the new object, which in there is called this.
class Pet {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const luna = new Pet("Luna", 3);
console.log(luna.name, luna.age);Prints
Luna 3
The rest of the explanation is in the lesson, which is part of the full plan.
Exercises in this lesson
You do them in the app, which checks them on the spot and explains why.
1. Predict the output
What does this code print?
2. Complete the code
Fill in the constructor so each book keeps its title.
3. Predict the output
Look at the order of the values. What does it print?
4. Multiple choice
new Pet("Max", 5)runs. Inside the constructor, what isthis?5. Find the bug
This program should print "Zoe 12". Which line has the bug?
6. Predict the output
What does this code print?
7. Predict the output
The room grows after it's created. What does it print?
8. Put the lines in order
Put in order the program that creates an order of 2 loaves at 35 each and prints its total.
9. Find the case that fails
greet(name)creates aPlayerand returns its greeting, like"Hi, Mia". If you don't give it a name, the player should be called"Guest". Which call fails?10. Predict the output
Who passes?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.