Methods
JavaScript · Unit 12: Classes and objects
- Full plan
- JavaScript
- 10 exercises
A method is a function that lives inside the class. You write it without function and call it with a dot and parentheses: r.area().
Inside, this is the object you called it with, so the method can use its data.
class Rect {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const r = new Rect(3, 4);
console.log(r.area());Prints
12
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 method that says how many 250 ml cups come out of the thermos.
3. Predict the output
Look at the last line. What does it print?
4. Predict the output
What does this code print?
5. Find the bug
This program should print 2, the lives Noah has left after crashing. Which line has the bug?
6. Complete the code
Fill in the blank so the jar has an
addmethod that stores coins.7. Find the bug
This program should print how many liters of paint the wall needs, 3. Which line has the bug?
8. Put the lines in order
Put the program in order:
usedrains the phone's battery and returns how much is left. The constructor fits on one line; it's the same as on several.9. Find the case that fails
count(names)puts each name into aGroupand returns how many people ended up in it. Theaddmethod shouldn't add the same person twice. Which call fails?10. Predict the output
Liam adds up his grocery bill. What does it print?
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.