5

Arrow function

ES6 introduced the concept of arrow functions, which is a new way of defining and writing functions. Although it looks like syntactic sugar for regular functions, the key difference between them is the this are bound to 060ee290c512e8. A lot of details this will not be covered in this article

Event listener callback

When writing JavaScript for the browser, we often create event listeners. E.g:

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', function() {
    this.classList.toggle('active');
  });
});

In the above example, nodelist.prototype.foreach() used to traverse eventtarget.addeventlistener() , and a regular function is used as click event exchange. This callback is used to switch between the active and inactive states of the clicked element . When using regular functions, the this in the callback will be bound to the element that triggered the event.

Use arrow functions as callbacks

The arrow function does not have its own binding to this . So what if the previous code segment is converted to an arrow function? Its this points to the global window object.

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', () => {
    this.classList.toggle('active'); // “this” 指向 “window”
    // Error: Cannot read property 'toggle' of undefined
  });
});

Since the window object does not have the classlist attribute, as long as the matching element is clicked, the code will throw an error, which triggers the event listener and executes the callback. But in general, the code may silently fail, for example, it is possible to check a condition that judgment for window always returns to false , and for a given element it should return true , which can cause a lot of trouble and wasting your time.

To solve this problem, you can simply pass the first parameter of the callback function and event.target or event.currenttarget . Which one you use depends on your needs:

const toggleElements = document.querySelectorAll('.toggle');
toggleElements.forEach(el => {
  el.addEventListener('click', (e) => {
    e.currentTarget.classList.toggle('active'); // 工作正常
  });
});

173382ede7319973.gif


This article first published WeChat public account: Front-end Pioneer

Welcome to scan the QR code to follow the official account, and push you fresh front-end technical articles every day

欢迎扫描二维码关注公众号,每天都给你推送新鲜的前端技术文章


Welcome to continue reading other highly praised articles in this column:



疯狂的技术宅
44.4k 声望39.2k 粉丝