0
0

More than 1 year has passed since last update.

【javascript】メソッドチェーン

Last updated at Posted at 2021-11-20

チェーンメソッド

異なるメソッドを連続して実行することができる。

case

  • Personクラスにhello,introduce,shakeHands,byeというメソッドがある。

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    hello(person) {
        console.log(`${this.name} says hello ${person.name}`);
    }

    introduce() {
        console.log(`Hi, I'm ${this.name}, ${this.age} years old.`);
    }

    shakeHands(person) {
        console.log(`${this.name} shake hands with ${person.name}.`);
    }

    bye(person) {
        console.log(`Goodbye, ${person.name}.`);
    }
}

const bob = new Person('Bob', 23);
const tim = new Person('Tim', 33);

bob.hello(tim);
bob.introduce();
bob.shakeHands(tim);
bob.bye(tim);
  • 実行するとそれぞれ以下の要素がコンソールに出力される。
    • Bob says hello Tim
    • Hi, I'm Bob, 23 years old.
    • Bob shake hands with Tim.
    • Goodbye, Tim
  • 問題は、実行する時にそれぞれ、のメソッドを以下のように実行することになる。
bob.hello(tim);
bob.introduce();
bob.shakeHands(tim);
bob.bye(tim);
  • これを以下のように連続して実行するにはどうするか?

bob.hello(tim)
   .introduce()
   .shakeHands(tim)
   .bye(tim)

結論

各メソッドの戻り値にthisを追加してPersonオブジェクトを返してあげる


hello(person) {
        console.log(`${this.name} says hello ${person.name}`);
        return this;
    }

なぜか?
* 最初のhallo()を実行した時にhalloにはPersonのオブジェクトが渡っていないため、連続して、メソッドを追加できない。

  • そこで、Personオブジェクトの各メソッドの戻り値にthisを渡すことで実行後もPersonオブジェクトを維持することができる。

    • thisにはpersonオブジェクトが存在しprototypeにはメソッドが格納されていることが確認できる。
    • スクリーンショット 2021-11-20 20.28.05.png
  • 最終的のコード


class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    hello(person) {
        console.log(`${this.name} says hello ${person.name}`);
        return this;
    }

    introduce() {
        console.log(`Hi, I'm ${this.name}, ${this.age} years old.`);
        return this;
    }

    shakeHands(person) {
        console.log(`${this.name} shake hands with ${person.name}.`);
        console.log(this)
        return this;
    }

    bye(person) {
        console.log(`Goodbye, ${person.name}.`);

    }
}

const bob = new Person('Bob', 23);
const tim = new Person('Tim', 33);

bob.hello(tim)
    .introduce()
    .shakeHands(tim)
    .bye(tim);

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0