将箭头函数和 event.target 与事件处理程序一起使用来获取范围而不是普通函数和 this 关键字?
Using arrow functions and event.target with event handlers to get scope instead of normal functions and the this keyword?
我的首选是写JS时使用箭头函数
我读了很多描述何时不使用箭头函数的文章,包括在 Whosebug 上回答的一个问题:
- when should I use arrow functions in ecmascript-6
- When 'Not' to Use Arrow Functions - Dmitri Pavlutin
- When You Should Not Use Arrow Functions - Javascript Tutorial
所有这些文章都指出在使用 eventHandlers 时不应使用箭头函数,因为 this
的范围被设置为全局而不是被单击的对象。但是,我一直在使用带有事件处理程序的箭头函数,如下所示:
button.addEventListener('click', (event) => {
const target = event.target
}
event.target
在使用箭头函数时为您提供事件范围。但是,有这么多文章建议不要在事件处理程序中使用箭头函数,我想知道我的方法是否有任何我可能遗漏的缺点?
However, with so many articles recommending against using arrow functions in event handlers, I am wondering if there are any disadvantages to my approach that I may have missed?
看起来你没有错过任何东西。您没有使用 .
你是
- 不使用
this
- 不使用
arguments
- 不使用
new
调用函数(浏览器也不会)
因此您可以选择任何一种形式。
如果我没记错的话 event.target
在旧版本的 Internet Explorer (< 9) 中不存在(而是 event.srcElement
),但是如果您使用的是箭头函数,您可能不会不关心已弃用的浏览器 ;)
我的首选是写JS时使用箭头函数
我读了很多描述何时不使用箭头函数的文章,包括在 Whosebug 上回答的一个问题:
- when should I use arrow functions in ecmascript-6
- When 'Not' to Use Arrow Functions - Dmitri Pavlutin
- When You Should Not Use Arrow Functions - Javascript Tutorial
所有这些文章都指出在使用 eventHandlers 时不应使用箭头函数,因为 this
的范围被设置为全局而不是被单击的对象。但是,我一直在使用带有事件处理程序的箭头函数,如下所示:
button.addEventListener('click', (event) => {
const target = event.target
}
event.target
在使用箭头函数时为您提供事件范围。但是,有这么多文章建议不要在事件处理程序中使用箭头函数,我想知道我的方法是否有任何我可能遗漏的缺点?
However, with so many articles recommending against using arrow functions in event handlers, I am wondering if there are any disadvantages to my approach that I may have missed?
看起来你没有错过任何东西。您没有使用
你是
- 不使用
this
- 不使用
arguments
- 不使用
new
调用函数(浏览器也不会)
因此您可以选择任何一种形式。
如果我没记错的话 event.target
在旧版本的 Internet Explorer (< 9) 中不存在(而是 event.srcElement
),但是如果您使用的是箭头函数,您可能不会不关心已弃用的浏览器 ;)