Introduction to the usage of JavaScript arrow functions
More concise syntax
##Let’s first define the function according to the conventional syntax:
function funcName(params) { return params + 2; } funcName(2); // 4
This function uses arrow functions and can be done with just one line of code!
var funcName = (params) => params + 2 funcName(2); // 4
Isn’t it cool! Although it is an extremely concise example, it well illustrates the advantages of arrow functions when writing code. Let’s take a deeper look at the syntax of arrow functions: [code ](parameters) => { statements }[/code]
If there are no parameters, it can be further simplified:
() => { statements }
If there is only one parameter, you can omit the brackets:
parameters => { statements }
If the return value is only one expression (expression), you can also omit the braces:
parameters => expression // 等价于: function (parameters){ return expression; }
Now that you have learned the syntax of arrow functions, let’s put it into practice. Open the Chrome browser developer console and enter:
var double = num => num * 2
We bind the variable double to an arrow function, which has a parameter num and returns num * 2. Call this function:
double(2); // 4 double(3); // 6
No binding of local this
Unlike ordinary functions, arrow functions do not bind this. In other words, the arrow function will not change the original binding of this. We use an example to illustrate:
function Counter() { this.num = 0; } var a = new Counter();
Because the keyword new construct is used, this in the Count() function is bound to a new Object and assigned to a. Printing a.num through console.log will output 0.
console.log(a.num); // 0
If we want to increase the value of a.num by 1 every second, how to achieve it? You can use the setInterval() function.
function Counter() { this.num = 0; this.timer = setInterval(function add() { this.num++; console.log(this.num); }, 1000); }
var b = new Counter(); // NaN // NaN // NaN // ..
You will find that a NaN is printed every second instead of the accumulated number . What went wrong? First use the following statement to stop the continuous execution of the setInterval function:
clearInterval(b.timer);
Let’s try to understand why the error occurred: According to the rules explained in the previous blog, first of all, the function setInterval is not used by a declared object When calling, the new keyword is not used, and bind, call and apply are not used. setInterval is just a normal function. In fact, this in setInterval is bound to the global object. We can verify this by printing this:
function Counter() { this.num = 0; this.timer = setInterval(function add() { console.log(this); }, 1000); } var b = new Counter();
You will find that the entire window object is printed. Use the following command to stop printing:
clearInterval(b.timer);
So, how do we solve this problem? Use arrow functions! Using arrow functions will not cause this to be bound to the global object.
function Counter() { this.num = 0; this.timer = setInterval(() => { this.num++; console.log(this.num); }, 1000); } var b = new Counter(); // 1 // 2 // 3 // ...
This bound through the Counter constructor will be retained. In the setInterval function, this still points to our newly created b object.
In order to verify what we just said, we can bind this in the Counter function to that, and then determine whether this and that are the same in setInterval.
function Counter() { var that = this; this.timer = setInterval(() => { console.log(this === that); }, 1000); } var b = new Counter(); // true // true // ...
clearInterval(b.timer);
Summary
- ##Arrow function writing code has a more concise syntax;
- This will not be bound.
The above is the detailed content of Introduction to the usage of JavaScript arrow functions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Users may have seen the term wapi when using the Internet, but for some people they definitely don’t know what wapi is. The following is a detailed introduction to help those who don’t know to understand. What is wapi: Answer: wapi is the infrastructure for wireless LAN authentication and confidentiality. This is like functions such as infrared and Bluetooth, which are generally covered near places such as office buildings. Basically they are owned by a small department, so the scope of this function is only a few kilometers. Related introduction to wapi: 1. Wapi is a transmission protocol in wireless LAN. 2. This technology can avoid the problems of narrow-band communication and enable better communication. 3. Only one code is needed to transmit the signal

Pubg, also known as PlayerUnknown's Battlegrounds, is a very classic shooting battle royale game that has attracted a lot of players since its popularity in 2016. After the recent launch of win11 system, many players want to play it on win11. Let's follow the editor to see if win11 can play pubg. Can win11 play pubg? Answer: Win11 can play pubg. 1. At the beginning of win11, because win11 needed to enable tpm, many players were banned from pubg. 2. However, based on player feedback, Blue Hole has solved this problem, and now you can play pubg normally in win11. 3. If you meet a pub

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

i5 is a series of processors owned by Intel. It has various versions of the 11th generation i5, and each generation has different performance. Therefore, whether the i5 processor can install win11 depends on which generation of the processor it is. Let’s follow the editor to learn about it separately. Can i5 processor be installed with win11: Answer: i5 processor can be installed with win11. 1. The eighth-generation and subsequent i51, eighth-generation and subsequent i5 processors can meet Microsoft’s minimum configuration requirements. 2. Therefore, we only need to enter the Microsoft website and download a "Win11 Installation Assistant" 3. After the download is completed, run the installation assistant and follow the prompts to install Win11. 2. i51 before the eighth generation and after the eighth generation

After updating to the latest win11, many users find that the sound of their system has changed slightly, but they don’t know how to adjust it. So today, this site brings you an introduction to the latest win11 sound adjustment method for your computer. It is not difficult to operate. And the choices are diverse, come and download and try them out. How to adjust the sound of the latest computer system Windows 11 1. First, right-click the sound icon in the lower right corner of the desktop and select "Playback Settings". 2. Then enter settings and click "Speaker" in the playback bar. 3. Then click "Properties" on the lower right. 4. Click the "Enhance" option bar in the properties. 5. At this time, if the √ in front of "Disable all sound effects" is checked, cancel it. 6. After that, you can select the sound effects below to set and click

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Dogecoin is a cryptocurrency created based on Internet memes, with no fixed supply cap, fast transaction times, low transaction fees, and a large meme community. Uses include small transactions, tips, and charitable donations. However, its unlimited supply, market volatility, and status as a joke coin also bring risks and concerns. What is Dogecoin? Dogecoin is a cryptocurrency created based on internet memes and jokes. Origin and History: Dogecoin was created in December 2013 by two software engineers, Billy Markus and Jackson Palmer. Inspired by the then-popular "Doge" meme, a comical photo featuring a Shiba Inu with broken English. Features and Benefits: Unlimited Supply: Unlike other cryptocurrencies such as Bitcoin

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.
