javascript · level 3 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A class is a blueprint, and new builds objects from it.
When you need many objects of the same shape, like orders or players, write a class. It is a blueprint. Each object built from it with new is an , with its own data but the same methods.
The runs once for each new, filling in the data. Inside any method, means the instance the method was called on, so this.items is that order's own array and nobody else's.
class Order {
constructor(customer) {
this.customer = customer;
this.items = [];
}
add(item, price) { this.items.push({ item, price }); }
total() {
return this.items.reduce((sum, line) => sum + line.price, 0);
}
}
const order = new Order("Ada");
order.add("tea", 2);
order.add("scone", 3);
console.log(`${order.customer} owes £${order.total()}`); Class names start with a capital letter, like Order, so they stand out from ordinary variables.
guess first
Two players, one blueprint. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Player {
constructor(name) {
this.name = name;
this.score = 0;
}
win() { this.score = this.score + 3; }
}
const a = new Player("Mo");
const b = new Player("Zoe");
a.win();
a.win();
console.log(a.score, b.score);
console.log(b);
your turn
Your turn. Teach a pet to speak.
In the first blank, reach this pet's own sound through this. Then give your pet a name and a sound.
fix it
The basket will not fill. Can you fix it?
- Read the error name. Which name on line 6 does JavaScript not know?
itemsbelongs to the instance, so inside a method you must reach it throughthis.- Change line 6 to
this.items.push(item);, then press run.
nailed it
you designed your own kind of object. :D
- A class is a blueprint;
newbuilds an instance. - The constructor sets up each instance's own data.
- Inside a method,
thisis the instance it was called on.
new words in your collection
- instance
- constructor
- this
This lesson isn’t saved. A free account remembers every lesson you finish.