Classes & prototypes
Computer Science · JavaScript
Question 1 of 10
0What does this JavaScript code log? class Rect { constructor(w, h) { this.w = w; this.h = h; } area() { return this.w * this.h; } } console.log(new Rect(3, 11).area());
Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.
How to type your answer
- Fractions: 3/4. Mixed numbers: 1 1/2.
- Decimals with a point or a comma: 0.75 or 0,75.
- Negative numbers start with a minus: -3/4.
- Percentages need the % sign: 75%.
Stuck? Read the explanation
Unlocks at a streak of 5 correct answers in a row.
Embed this practice on your site or class page
Paste this HTML into your page. Students practise right there; it is free and needs no account.
Classes & prototypes explained
A class is a template for creating objects that share methods and properties. In JavaScript, classes are a syntax over the older prototype system, in which every object can inherit properties from another object.
The constructor runs when new is used and sets each new object's own properties. Other methods written in the class body live on the class's prototype and are shared by all instances. extends creates a subclass, and super calls the parent constructor or method.
class Account {
constructor(owner, balance) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
return this;
}
}
const acc = new Account("Ada", 100).deposit(50);
console.log(acc.balance);
When a property is read, JavaScript checks the object and then follows the prototype chain upward until it finds the property. Object.getPrototypeOf(acc) === Account.prototype is true. Caveat: unlike function declarations, class declarations are not hoisted for use, so using a class before its line throws a ReferenceError.
Worked example
new Account("Ada", 100) creates an object with balance 100. deposit(50) adds 50 and returns this, so the call can be chained. The balance is 150, and the program prints 150.
What you will practise
New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.
Example questions
Easy
What does this JavaScript code log?
class Rect { constructor(w, h) { this.w = w; this.h = h; } area() { return this.w * this.h; } } console.log(new Rect(9, 5).area());
Medium
What does this JavaScript code log?
class Animal { value() { return 7; } } class Dog extends Animal { value() { return super.value() + 6; } } console.log(new Dog().value());
Hard
What does this JavaScript code log?
function Counter() {} Counter.prototype.step = 5; const c = new Counter(); Counter.prototype.step = 18; c.step = 4; const before = c.step; delete c.step; console.log(before + c.step);