One blueprint, many objects

INPUT · Slides

Calling one method from another

01 / 04

When the same work shows up in two places

Say the work of "showing the name as a sort of heading" turns up in method after method.

Write the same thing twice and there are two places to fix. Better to gather it into one method and call that.

02 / 04

Call it with this.methodName()

To call another of your own methods from inside a method, you use this as well. You write it like this.sign();.

The same shape as reading a property. The only difference is whether there is a ( ) on the end.

class Robot {  constructor(name) {    this.name = name;  }  sign() {    console.log(`--- ${this.name} ---`);  }  report() {    this.sign();    console.log("all clear");  }}const r = new Robot("Clank");r.report();

Result

--- Clank ---
all clear

03 / 04

There is a form that catches the return value

If the method you call sends a value back with return, you can use that value as it stands.

Split into "a method that works something out" and "a method that shows it" and, whether you want to change the sum or change the display, you know exactly which one place to touch.

class Shop {  constructor(price, count) {    this.price = price;    this.count = count;  }  subtotal() {    return this.price * this.count;  }  show() {    console.log(`total ${this.subtotal()} yen`);  }}const s = new Shop(120, 4);s.show();

Result

total 480 yen

04 / 04

Split small and build up

Rather than cramming everything into one method, making several small methods and putting them together reads better.

The knack is to split them small enough that the name tells you what they do. Off you go.