0

Why 'this' works as expected in this context

const p = document.querySelectorAll('p')

function changeColor() {
    this.style.backgroundColor = 'red'
}

p.forEach(element => element.addEventListener('click', changeColor)

But fails in this other?

const p = document.querySelectorAll('p')

const changeColorArrow = () => this.style.backgroundColor = 'red'

p.forEach(element => element.addEventListener('click', changeColorArrow)

I know the 'this' keyword works differently in arrow functions and traditional functions, but as a beginner, I can't see where exactly it fails.

Is it ok to work with the first function (changeColor) or is there a smarter way to make the arrow function (changeColorArrow) work in this case?

Thank you!

  • In the first sample `changeColor` gets bound to the element, and so `this` will refer to the element being clicked. In the second sample, `this` uses the value of `this` at the point in which the function was defined, and does not get bound. If you would like to use an arrow function, one valid way of defining it would be as follows: `const changeColorArrow = (event) => event.currentTarget.style.backgroundColor = 'red'`. `event.currentTarget` refers to whichever element triggered the `click` (or other) event. – Travis Valenti Jul 30 '21 at 00:41
  • For more information, see: - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Travis Valenti Jul 30 '21 at 00:41

0 Answers0