LoginSignup
0
1

More than 1 year has passed since last update.

【JavaScript】functionとアロー関数のthisの違い

Posted at

ダメな例

document.addEventListener("turbolinks:load", () => {
    $('#post_image').on('change', () => {
      var size_in_megabytes = this.files[0].size/1024/1024;
      if (size_in_megabytes > 5){
        alert("アップロード可能なファイルサイズは5MBまでです。より小さいサイズのファイルを選んでください。");
        $('#post_image').val("");
      }
    });
  });

このエラーになる

image_size.js:4 Uncaught TypeError: Cannot read property '0' of undefined
at HTMLInputElement.<anonymous> (image_size.js:4)

() => {}内のthisはaddEventListnerメソッド実行時のスコープであるグローバルスコープ(document)を指す。

this.filesは定義されていない(undefinedだ)から'0'は読み込めません!とのこと

document.addEventListener("turbolinks:load", () => {
    $('#post_image').on('change', () => {
      var size_in_megabytes = this.files.size/1024/1024;
      if (size_in_megabytes > 5){
        alert("アップロード可能なファイルサイズは5MBまでです。より小さいサイズのファイルを選んでください。");
        $('#post_image').val("");
      }
    });
  });
image_size.js:4 Uncaught TypeError: Cannot read property 'size' of undefined
at HTMLInputElement.<anonymous> (image_size.js:4)

this.filesは定義されていない(undefinedだ)から'size'は読み込めません!とのこと

うまくいく例

  document.addEventListener("turbolinks:load", () => {
    $('#post_image').on('change', function(){
      var size_in_megabytes = this.files[0].size/1024/1024;
      if (size_in_megabytes > 5){
        alert("アップロード可能なファイルサイズは5MBまでです。より小さいサイズのファイルを選んでください。");
        $('#post_image').val("");
      }
    });
  });

function(){}内のthisはaddEventListnerメソッドを保持する$('#post_image')オブジェクト(DOM)を指す

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