1
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 1 year has passed since last update.

Queryのeachメソッドなどに使用するコールバック関数でアロー関数を使用するには注意が必要

Last updated at Posted at 2023-02-26

jQueryで要素でeachメソッドを使用する際に、コールバック関数にアロー関数を使用していたら、問題があったので記事を書きたいと思います。

アロー関数内では$(this)がwindow要素になってしまう

コールバック関数にfunction(){}を使用し、関数内で$(this)と書くと、順番に取り出す要素を取得することができる。

<div>div1</div>
<div>div2</div>
<div>div3</div>
$('div').each(function(){
    console.log($(this)); //div要素が一つづつ出力される
});

しかし、コールバック関数をアロー関数にした場合、$(this)がwindow要素になる。

$('div').each(() => {
    console.log($(this)); //window要素が出力される
});

なぜこうなるのか?

アロー関数は、callなどのメソッドを使用すると、thisの指定ができないようです。
参考: https://qiita.com/suin/items/a44825d253d023e31e4d

このことから、eachなどのメソッドでは、内部でcallなどのメソッドでthisに順番の要素を指定して、コールバック関数を使用しているため、コールバック関数をアロー関数で指定すると、thisが指定できず、グローバルに定義されたthisを使用してしまうために起きている........のかもしれない。

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