试图理解我代码中的“this”关键字

时间:2021-07-30 00:31:52

标签: javascript events this

为什么“this”在这种情况下按预期工作

const p = document.querySelectorAll('p')

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

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

但在另一个方面失败了?

const p = document.querySelectorAll('p')

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

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

我知道“this”关键字在箭头函数和传统函数中的作用不同,但作为初学者,我看不出它到底在哪里失败。

在这种情况下可以使用第一个函数 (changeColor) 还是有更聪明的方法使箭头函数 (changeColorArrow) 起作用?

谢谢!

0 个答案:

没有答案
相关问题