0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JS】チェーンメソッドのTips

Posted at

チェーンメソッド's Tips

いくつもメソッドを連続で実行するためには、一工夫するだけで実行できます。
それは、メソッド末尾にreturn this;と返すだけです。
以下の例では、最後にthisを返すことで、Personオブジェクトを返すことになるので、チェーンにしてもエラーが発生せずに実行出来ます。

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

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

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

// インスタンスを生成
const bob = new Person('Bob', 23);

// チェーンメソッドで実行する
bob.hello(bob).bye(bob);
// => 'hello bob' 'Goodbye, bob'
0
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?