在决定如何将回调传递给addEventListener时,我应该考虑什么,给定以下方法?
element.addEventListener('click', function(){
// ...
});
要么
function doSomething(){
// ...
}
element.addEventListener('click', doSomething);
要么
element.addEventListener('click', function doSomething(){
// ...
});
最佳答案 您的第一个代码段使用匿名函数. Todd Motto has written an article列出了为什么要避免在回调函数中使用匿名函数的一些原因:
- Are more difficult to debug
- Cannot be reused
- Cannot be tested easily
- Do not describe the role of the function
- Make code lack structure
- Create messier/unclear code
- Documentation will suffer (things like jsDoc)