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'); // 工作正常
});
});
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:
- Deep understanding of Shadow DOM v1
- teaches you step by step to use WebVR to realize virtual reality games
- 13 modern CSS frameworks to help you improve development efficiency
- Quickly get started with BootstrapVue
- JavaScript engine work? Everything you need to know from call stack to
- WebSocket combat: real-time communication between Node and React
- 20 interview questions about Git
- depth analysis of Node.js console.log
- What exactly is Node.js?
- 30 minutes to build an API server
- Javascript object copy
- Programmers have a monthly salary of less than 30K before the age of 30, so what should they do?
- 14 best JavaScript data visualization libraries
- 8 top VS Code extension plug-ins for the front end
- Node.js Multithreading Complete Guide
- 4 schemes and implementations of converting HTML to PDF
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。