JavaScript ES6 Arrow Function Guide

Source: Internet
Author: User
Tags setinterval

Objective

The Fat arrow function (FAT arrow functions), also known as the arrow function, is a new feature from ECMAScript 2015 (also known as ES6). It is rumored that the syntax of the arrow function => is CoffeeScript  affected, and that it shares the CoffeeScript => context as in the syntax this .

The arrow functions are produced primarily by two purposes: a more concise syntax and shared keywords with the parent scope this . Next, let's look at a few detailed examples.

The new function syntax

The traditional JavaScript function syntax does not provide any flexibility, and every time you need to define a function, you must enter it function () {} . CoffeeScriptOne of the reasons why the fire is so hot today is that it has a more concise function syntax. The more concise function syntax is particularly noticeable in scenarios with a large number of callback functions, let's Promise look at a chain example:

function Getverifiedtoken (selector) {  return getusers (selector)    . Then (function (users) {return users[0];})    . then (Verifyuser) and then    (function (user, Verifiedtoken) {return verifiedtoken;})    . catch (function (err) {log (err.stack);});}

Here is the code after refactoring using the new arrow function syntax:

function Getverifiedtoken (selector) {  return getusers (selector)    . Then (users = Users[0])    . Then ( Verifyuser)    . Then (user, Verifiedtoken) = Verifiedtoken)    . catch (Err = log (Err.stack));}

Here are a few notable points to note:

    • functionAnd all {} disappear, all the callback functions appear only in one line.

    • When there is only one parameter, () it disappears (the rest parameter is an exception, such as (...args) => ... ).

    • When it {} disappears, the return keyword disappears. The single-line arrow function provides an implicit return (such a function is often used as a LAMDA function in other programming languages).

The last requirement above is highlighted here. Implicit occurs only when the arrow function is a single-line form return . When an arrow function is accompanied {} by a declaration, even if it is a single line, it does not have an implicit return :

Const Getverifiedtoken = selector = {  return getusers ()    . Then (users = Users[0])    . Then (Verifyuser) C6/>.then (user, Verifiedtoken) = Verifiedtoken)    . catch (Err = log (Err.stack));}

If there is only one declaration in our function (statement), we can not write it {} , so that it looks CoffeeScript very similar to the function in:

Const Getverifiedtoken = selector =  getusers ()    . Then (users = Users[0])    . Then (Verifyuser)    . Then (user, Verifiedtoken) = Verifiedtoken)    . catch (Err = log (err.stack));

You are not mistaken, the above example is perfectly legal ES6 syntax. When we talk about an arrow function that contains only one declaration (statement), this does not mean that the declaration cannot be broken into multiple lines of writing.

Here's a pit, {} how do we return an empty object () when we ignore it {} ?

Const EMPTYOBJECT = () = {};emptyobject (); // ?

Unfortunately, the empty object {} and the blank function code block look exactly the same. {} In the example above, emptyObject it {} will be interpreted as a blank function code block, so emptyObject() it will be returned undefined . If you want to explicitly return an empty object in an arrow function, you will have to include it in a {} pair of parentheses ( ({}) ):

Const EMPTYOBJECT = () = ({}); Emptyobject (); // {}

The following is a more complete example:

function () {return 1;} () = {return 1;} () = 1 function (a) {return a * 2;} (a) = = {return a * 2;} (a) = a * 2a = A * 2 function (A, b) {return a * b;} (A, b) = = {return a * b;} (A, b) = = A * b function () {return arguments[0];} (.. args) = Args[0] () = {}//undefined () = ({})//{}
This

JavaScriptthisThe story is already very old, and every function has its own context. The purpose of the following example is jQuery to show a clock that will be updated every second:

$ ('. Current-time '). each (function () {  setinterval (function () {    $ (). Text (Date.now ());  }, 1000);});

When trying to setInterval this refer to DOM elements in a callback, unfortunately, we get only one that belongs to the context of the callback function itself this . A common solution is to define one that or a self variable:

$ ('. Current-time '). each (function () {  var-self = this;   SetInterval (function () {    $ (self). Text (Date.now ());  }, 1000);});

But when you use the FAT arrow function, the problem is no longer there. Because it does not produce a context that belongs to it itself this :

$ ('. Current-time '). each (function () {  setinterval (() = () = $ (this). Text (Date.now ()), 1000);});
Arguments variable

The other difference between an arrow function and a normal function is that it does not have its own arguments variables:

function log (msg) {  const PRINT = () = Console.log (Arguments[0]);  Print (' LOG: ${msg} ');} Log (' Hello '); Hello

Again, the arrow functions do not belong to their own this and arguments . However, you can still pass through the rest parameter to all incoming parameter arrays:

function log (msg) {  const PRINT = (.... args) = Console.log (Args[0]);  Print (' LOG: ${msg} ');} Log (' Hello '); Log:hello
About yield

The arrow function cannot be used as a generator function.

At last

The arrow function is one of my favorite ES6 features. Use => to replace function is very convenient. But I've seen code that only uses it => to declare functions, and I don't think that's a good idea, because => it also provides a unique feature that distinguishes it from tradition function . I personally recommend that you use it only if you need to use the new features it provides:

    • Implicit when there is only one declaration (statement) statement return .

    • Needs to be used in the parent scope this .

JavaScript ES6 Arrow Function Guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.