One blueprint, many objects

INPUT · Slides

Handing values over as you make one

01 / 05

The problem of only ever making the same contents

With last lesson's way, every new gives you a real one with exactly the same contents.

But robots have different names one from the next, and products have different prices one by one. What you want is to say "make it with this value" as you make it.

02 / 05

Write parameters on the constructor

Write parameters — places for the values you catch — inside the brackets, as in constructor(name, power). You hand them over inside the new's brackets, as in new Robot("Clank", 10).

Exactly the machinery you learned with functions. They are caught in the order you hand them over.

class Robot {  constructor(name, power) {    this.name = name;    this.power = power;  }}const r = new Robot("Clank", 10);console.log(r.name);console.log(r.power);

Result

Clank
10

03 / 05

Change what you hand over and it is a different one

One blueprint still, and now you can make any number of real ones with different contents.

This is a class at its best. Same shape, separate contents. A blueprint for turning things out, exactly as advertised.

class Robot {  constructor(name, power) {    this.name = name;    this.power = power;  }}const a = new Robot("Clank", 10);const b = new Robot("Beep", 18);console.log(a.name);console.log(b.name);

Result

Clank
Beep

04 / 05

The same name on the left and the right is fine

this.name = name; looks a little odd with the same name on both sides, but the meanings are cleanly apart.

  • the left this.namea property of the real one being made
  • the right namethe argument just caught

Read it as "copy the value I caught onto the real one's property".

05 / 05

You can do sums with what you caught

Inside a constructor is a place for ordinary work. You can even make another property out of what you caught.

So the total is ready the moment it is made. Off you go.

class Order {  constructor(price, count) {    this.price = price;    this.count = count;    this.total = price * count;  }}const o = new Order(160, 3);console.log(o.total);

Result

480