では HTML ボタン+クリックイベント を使って、関数式とアロー関数の this の違いを体感できるサンプルを作ります。
ブラウザにコピーしてそのまま動かせます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>this の違いデモ</title>
</head>
<body>
<h2>this の違いデモ</h2>
<button id="btnRegular">通常の関数</button>
<button id="btnArrow">アロー関数</button>
<script>
// オブジェクトを作る
let obj = {
name: "太郎",
// 1. 通常の関数でクリックイベント
regularFunc: function() {
document.getElementById("btnRegular").addEventListener("click", function() {
console.log("通常の関数内 this.name:", this.name);
alert("通常の関数内 this.name: " + this.name);
});
},
// 2. アロー関数でクリックイベント
arrowFunc: function() {
document.getElementById("btnArrow").addEventListener("click", () => {
console.log("アロー関数内 this.name:", this.name);
alert("アロー関数内 this.name: " + this.name);
});
}
};
// 関数を実行してイベントを設定
obj.regularFunc();
obj.arrowFunc();
</script>
</body>
</html>
HTML💡 ポイント解説
- 通常の関数 (
function() {...})- クリックされたボタンが
thisになる this.nameはundefinedになる(ボタンにはnameプロパティがないため)
- クリックされたボタンが
- アロー関数 (
() => {...})- 定義時の
this(外側 obj の this = obj)をそのまま使う this.nameは"太郎"が表示される
- 定義時の
See the Pen this difference demo by MONO365 -Color your days- (@monoqlo365) on CodePen.

