Static methods
JavaScript · Unit 12: Classes and objects
- Full plan
- JavaScript
- 9 exercises
You've already used a method that's called with the class name and not with an object: Object.keys(obj). It's a static method: it belongs to the class, not to each object.
You write it with static in front and use it without new.
class Temp {
static toF(c) {
return c * 9 / 5 + 32;
}
}
console.log(Temp.toF(20));
console.log(Temp.toF(100));Prints
68 212
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 blank to convert 30 °C to Fahrenheit.
3. Put the lines in order
Put in order the program that adds 8% sales tax to a price of 100.
4. Find the bug
This program should print 12, the area of the rectangle. Which line has the bug?
5. Multiple choice
In a
Studentclass, which of these methods makes the most sense asstatic?6. Find the bug
This program should print 77, today's 25 °C in Fahrenheit. Which line has the bug?
7. Predict the output
Something the example did is missing here. What does it print?
8. Complete the code
fromMinutescreates aClockfrom minutes: 135 is 2 hours and 15 minutes. Fill in the blank so it prints "2 15".9. Predict the output
The shopping list arrives as text. 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.