javascript メソッドチェーンを作成する

javascript メソッドチェーンを作成する

javascriptで、メソッドチェーンを作成するサンプルコードを記述してます。ブラウザは、chromeを利用してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

メソッドチェーン作成

「javascript」では、以下のように「return this」で「thisオブジェクト」を戻り値にすることで、メソッドチェーンを実装することが可能です。

const hoge = {
  name: 'yamada',
  age: 28,
  
  getName: function() {
      console.log( this.name );
      return this;
  },
  getAge: function() {
      console.log( this.age );
      return this;
  }
}

hoge.getName().getAge();
// yamada
// 28

サンプルコード

以下は、
「実行」ボタンをクリックすると、メソッドチェーンを利用して要素に値を表示する
サンプルコードとなります。

※cssには「tailwind」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>

  const hoge = {
    str1: 'Hello',
    str2: 'World',

    getHello: function () {
      result1.innerHTML = this.str1;
      return this;
    },
    getWorld: function () {
      result2.innerHTML = this.str2;
      return this;
    }
  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge.getHello().getWorld(); }; // document.getElementById('btn');を省略    
  }

</script>

<body>
  <div class="container mx-auto my-56 w-56 px-4">

    <div class="flex justify-center">
      <p id="result1" class="bg-purple-500 text-white py-2 px-4 rounded-full mb-3 mt-4">結果1</p>
      <p id="result2" class="bg-purple-500 text-white py-2 px-4 rounded-full mb-3 mt-4">結果2</p>
    </div>

    <div class="flex justify-center">

      <button id="btn" type="button"
        class="mt-5 bg-transparent border border-pink-500 hover:border-pink-300 text-pink-500 hover:text-pink-300 font-bold py-2 px-4 rounded-full">
        実行
      </button>
    </div>
  </div>

</body>

</html>

値が表示されていることが確認できます。