本記事では、JavaScriptでaddEventListenerメソッドのコールバック関数をfunctionからアロー関数に変更したらthisが使えなくなった時の原因と対処法について解説しています。
JavaScriptの学習におすすめ参考書
改訂3版JavaScript本格入門 ~モダンスタイルによる基礎から現場での応用まで
先輩くん
10万部突破したJavaScriptの本が大幅増補改訂し7年ぶりに発売されたよ!
後輩ちゃん
最新の基本文法から、開発に欠かせない応用トピックまで学ぶことが出来るよ!
綺麗なコードが書けるようになる!
リーダブルコード-より良いコードを書くためのシンプルで実践的なテクニック
先輩くん
より良いコードを書きたい人におすすめの本だよ!
後輩ちゃん
10以上前の書籍ですが、内容は今でも役に立つものばかりです!
原因と対処法
まず始めにthisが使えなくなった原因は、アロー関数のthisが要素を参照しているのではなくwindowオブジェクトを参照しているからです。
※アロー関数内のthisは必ずwindowオブジェクトを参照するとは限りませんが、function→アロー関数にしたらthisが使えなくなったと考えるとwindowオブジェクトを参照している可能性が高いです。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p id="sample">hoge</p>
<script>
const el = document.querySelector("#sample");
el.addEventListener("mouseover", function () {
console.log(this); // <p id="sample"> hoge</p>
this.style.color = "red";
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p id="sample">hoge</p>
<script>
const el = document.querySelector("#sample");
el.addEventListener("mouseover", () => {
console.log(this); // Window {...}
this.style.color = "red";
});
</script>
</body>
</html>
上記のコードはfunctionとアロー関数を使用して同じ処理を実装したものです。やはり、アロー関数ではthisがwindowオブジェクトを参照としているため正しく動作しません。
これを正しく動作させるには、下記のようにコードを変更してあげる必要があります。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p id="sample">hoge</p>
<script>
const el = document.querySelector("#sample");
el.addEventListener("mouseover", (e) => {
console.log(e.target); // <p id="sample">hoge</p>
e.target.style.color = "red";
});
</script>
</body>
</html>
コールバック関数に引数をセットし、「引数.target」でイベントが発火した要素を特定することが出来ます。後はここにfunctionと同様の処理を記述すれば解決です。