this を使わないイベントハンドラの書き換え
JavaScript で this を使わないイベントハンドラの書き換え
code:vanilla.js
/**
* this を使わないイベントハンドラの書き換え
*/
// 1. jQuery の場合
// --------------------------------------------------
$(foo).on('click', (e) => {
// $(this) は使わず、$(e.currentTarget) を使う
// ※ e.currentTarget はイベントを登録した要素自身を指す
const $el = $(e.currentTarget);
$el.addClass('is-active');
console.log($el.data('id'));
});
// 2. Vanilla JS (純粋な JavaScript) の場合
// --------------------------------------------------
const bar = document.querySelector('#bar');
bar.addEventListener('click', (e) => {
// this は使わず、e.currentTarget を使う
const el = e.currentTarget;
el.classList.add('is-active');
console.log(el.dataset.id);
});
// 3. 配列処理 (Array.prototype.forEach など) の場合
// --------------------------------------------------
const items = document.querySelectorAll('.item');
// 第2引数の thisArg を使わず、アロー関数のスコープを利用する
items.forEach((item) => {
item.style.color = 'red';
});
// 4. クラスを使わない「機能の塊」の作り方 (代替案)
// --------------------------------------------------
const createCounter = (initialValue = 0) => {
let count = initialValue; // 閉じたスコープ(隠蔽)
return {
increment: () => ++count,
decrement: () => --count,
getValue: () => count
};
};
const myCounter = createCounter(10);
console.log(myCounter.increment()); // 11