×

javascript · level 3 · unit 2 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.