01 / 04
One blueprint, many objects
INPUT · Slides
Work that runs by itself as you make one
02 / 04
Write a constructor
Write constructor() { } inside a class's { } and the work inside it runs by itself, exactly once when you new. This is called a constructor — the work done when one is made.
There is no instruction anywhere to call it. The point is that it runs of its own accord the moment you new.
class Robot { constructor() { console.log("a robot is made"); }}const r = new Robot();r.name = "Clank";console.log(r.name);Result
a robot is made Clank
03 / 04
It runs as many times as you make one
new once, it runs once; new three times, three times. Once per instance.
Look at the order of the output and you can see it running the moment the line with the new on it is reached.
class Robot { constructor() { console.log("assembly complete"); }}const a = new Robot();a.name = "Clank";const b = new Robot();b.name = "Beep";console.log(a.name);console.log(b.name);Result
assembly complete assembly complete Clank Beep
04 / 04
For now it is a fixed set of contents
Here we only put a message out, but what you really want to do is get the properties ready.
For that you need a way of writing "the real one currently being made". That comes next lesson. Off you go.