LoginSignup
1
0

More than 3 years have passed since last update.

[JavaScript] thisを使用する理由

Posted at

概要

フロントエンド初心者による学習忘備録。
本投稿ではJavaScript(jQuery)で使用するthisについてまとめる。

環境

  • jquery-3.5.1.min.js
<script src="./js/vendor/jquery-3.5.1.min.js"></script>

thisを使用するメリット

メリットとして以下3点が主に挙げられる。

  • 処理のパフォーマンス向上
  • コードの流用
  • 複数のセレクタを指定した場合の処理の切り分け

パフォーマンス向上

jQueryの処理はメソッドチェーンとして順に処理される仕組みであり、ブラウザは指定されたセレクタを手がかりにHTMLから要素を集めるが、thisを使用しないとメソッドが実行されるたび毎回集めることになりCPUに負荷が掛かってしまう。

$(function () {
  $('.test').on('click', function () {
    $('.test').css('color', '#ebc000');
  });
});

以下のように変更する。

$(function () {
  $('.test').on('click', function () {
    // thisは上の状態を保持している
    $(this).css('color', '#ebc000');
  });
});

コードの流用

以下はそれぞれのクラスに対してcssのプロパティを変更する処理だが、内側の処理に重複が見受けられる。

$(function () {
  $('.test').on('mouseover', function () {
    $('.test').css('color', '#ebc000')
  });
});

$(function () {
  $('.test-class').on('mouseover', function () {
    $('.test-class').css('color', '#ebc000')
  });
});

内側のcssを変更する処理は同じのため、thisを使用し以下のように処理を簡潔にすることがベスト。

$(function () {
  function colorChange() {
    $(this).css('color', '#ebc000')
  };

  $('.test').on('mouseover', colorChange);
  $('.test-class').on('mouseover', colorChange);
});

処理の切り分け

以下処理では複数のセレクタを指定しcssメソッドを実行しているが、いずれかの要素にイベントが発生した際指定されている全ての要素にメソッドが反映されてしまう。

$(function () {
  $('header, .test-class, .test').on('mouseover', function () {
    $('header, .test-class, .test').css(
      'background-color', '#ae5e9b'
    );
  });
});

thisを使用し以下のように変更することで、各セレクタに対しそれぞれメソッドが反映されるようになる。

$(function () {
  $('header, .test-class, .test').on('mouseover', function () {
    $(this).css(
      'background-color', '#ae5e9b'
    );
  });
});

1
0
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
1
0