One blueprint, many objects

INPUT · Slides

Looking at your own contents from a method

01 / 04

this inside a method

The this that turned up in the constructor works inside a method too.

Inside a method, this means the thing that method was called on. Write r.greet() and this is r.

02 / 04

Read your own properties

Write this.name and you can read the name that thing holds.

No more need to have the name handed in as a parameter. You know your own business.

class Robot {  constructor(name) {    this.name = name;  }  greet() {    console.log(`I am ${this.name}`);  }}const r = new Robot("Clank");r.greet();

Result

I am Clank

03 / 04

The result changes with who you called

The same greet() is being called and yet different words come out. Because this points at a different one.

This is the machinery of "write the behaviour once on the blueprint and get a different result per real one".

class Robot {  constructor(name) {    this.name = name;  }  greet() {    console.log(`I am ${this.name}`);  }}const a = new Robot("Clank");const b = new Robot("Beep");a.greet();b.greet();

Result

I am Clank
I am Beep

04 / 04

You can overwrite too

this.property is not only for reading; it works for overwriting as well.

With that, an instance can now change its own state. Off you go.

class Counter {  constructor() {    this.count = 0;  }  add() {    this.count += 1;  }}const c = new Counter();c.add();c.add();console.log(c.count);

Result

2