I am working on a test case for javascript bind this
keyword with click eventlistener to arrow function and adding class using this
keyword, I have tried to bind my function but every time this
keyword is pointing to window object, which I want to point to event object.
here is my code.
const cards = document.querySelectorAll(".card");
var isFlipped = false;
var firstCard;
var secondCard;
const flip = ( ) => {
console.log(this);
this.classList.add("flip");
if (!isFlipped) {
isFlipped = true;
firstCard = this;
} else {
secondCard = this;
console.log(firstCard);
console.log(secondCard);
}
}
Array.from(cards).map(card => card.addEventListener("click", flip.bind(this) ));
here is the HTML incase you want to check
<div class="gameContainer">
<div class="container">
<h1 class="text-center text-white display-4">How is your memory</h1>
</div>
<div class="card" data-image="evilface">
<img src="evilface.png" class="front flip" alt="evilface" />
<img src="lco.png" class="back" alt="lco" />
</div>
</div>
Note: of-course I can make arrow function to normal function and this will work as exprected, but I want this with arrow function.