One blueprint, many objects

INPUT · Slides

Giving it contents with this

01 / 04

The word for the real one being made

Inside a constructor there is a word for the very real one currently being made. That word is this.

this can be used like a variable, and writing this.name = value; gives that real one a property.

02 / 04

How to write it

The constructor runs the moment you new, and the values go into this. So by the time it is finished, the contents are already there.

To read them, from outside you just write variable.name as usual.

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

Result

Clank
10

03 / 04

How is that different from adding by hand?

Before, you wrote the .name = ... yourself after the new. That way an instance you forgot could slip in among them.

Write it on the blueprint and anything made from that class is certain to have the same shape. Matched shapes make everything downstream far easier to write.

class Robot {  constructor() {    this.power = 10;  }}const a = new Robot();const b = new Robot();console.log(a.power);console.log(b.power);

Result

10
10

04 / 04

Still the same contents every time

Right now you write fixed values, so however many you make the contents are the same.

To give each real one different contents, hand a value over as you make it. That is next lesson. Off you go.