ECMASCRIPT6 's new feature arrow function (arrows functions) Detailed Introduction _ Basics

Source: Internet
Author: User

The arrow function is one of the most recent updates to ECMAScript 6. It introduces a new syntax for defining functions with an "arrow" (=>), which ... It's a fortress. The main difference between an arrow function and a traditional JavaScript function is the following:
1. The association to this. The value of this is built into the function, depending on where the arrow function is defined, not the context in which the arrow function executes.
2.new is not available. The arrow function cannot instantiate an object using the New keyword, or it will be an error.
3.this immutable. The function is built-in this immutable and is constant in the entire execution environment of the function body.
4. No arguments objects. It is also not possible to access incoming parameters through the arguments object. Can only be done using explicit naming or other ES6 new attributes.

The existence of these differences can be justified. First, the binding to this is one of the common sources of JavaScript errors. It is easy to lose built-in values of functions, or to produce unexpected results. Second, restricting the arrow function to use the fixed this reference facilitates JavaScript engine optimization processing.

First, the grammar

The syntax for an arrow function is simple, it defines the argument, and then the arrow and the body of the function. Arguments and themes can be used in a more concise format because they are different. The following example uses an arrow function that passes a parameter and returns a value.

Copy Code code as follows:

var reflect = value => value;
Equivalent to:

var reflect = function (value) {
return value;
};

You can see, pass a parameter to write directly, do not need to add parentheses. The arrow points to the body of the function, but the body of the function is also simply a return statement, so there is no need to enlarge the parentheses. The function is constructed and then assigned to reflect for reference.
If you want to pass in more than one parameter, you should add parentheses. For example:

Copy Code code as follows:

var sum = (NUM1, num2) => num1 + num2;
Equivalent to:
var sum = function (NUM1, num2) {
return NUM1 + num2;
};

The sum () method adds the two parameters and then the result is returned. The only difference between the previous example is that two arguments are passed in, so enclose them in parentheses. It is the same as a traditional function, separating the incoming arguments with commas in parentheses. Similarly, if the function does not need to pass in an argument, it is replaced with an empty parenthesis.

Copy Code code as follows:
var sum = () => 1 + 2;
Equivalent to:
var sum = function () {
return 1 + 2;
};

If you want to use a standard function body, or if more statements are to be executed in a function body, enclose the function body in curly braces and explicitly define the return value. For example:

Copy Code code as follows:

var sum = (NUM1, num2) => {return num1 + num2;}
Equivalent to:
var sum = function (NUM1, num2) {
return NUM1 + num2;
};

The parts within curly braces are basically equivalent to traditional functions, except that the arguments parameter is not available.
Because curly braces are flags for function bodies. The arrow function, if you want to return a custom object, must enclose the object in parentheses first. For example:

Copy Code code as follows:

var gettempitem = id = > ({
Id:id,
Name: "Temp"
});
Equivalent to:
var Gettempitem = function (ID) {
return {
Id:id,
Name: "Temp"
};
};

As you can see in the example above, using parentheses with curly braces is the object's definition, not the body of the function.

Second, the use

One of the most common errors in JavaScript is the internal this association of functions. Because this is a value based on the current execution environment of the function, it will be misunderstood at the time of the call, resulting in an impact on other unrelated objects. See the following example:

Copy Code code as follows:

var Pagehandler = {
ID: "123456",
Init:function () {
Document.addeventlistener ("click", Function (event) {
This.dosomething (Event.type); Error
}, False);
},
Dosomething:function (type) {
Console.log ("Handling" + Type + "for" + this.id);
}
};

In this code, it is intended that the Pagehandler init () method be used to build the interaction and Invoke this.dosomething () in the Click event handler function. However, the code was not executed as designed, and the runtime this point to the global object instead of Pagehandler, causing an error in the this.dosomething () invocation because the DoSomething method does not exist in the global object.
Of course, you can use BIND () in a function to explicitly associate this with Pagehandler, see below:

Copy Code code as follows:

var Pagehandler = {

ID: "123456",

Init:function () {
Document.addeventlistener ("Click", (Function (event) {
This.dosomething (Event.type);
}). bind (this), false);
},

Dosomething:function (type) {
Console.log ("Handling" + Type + "for" + this.id);
}
};

Although it looks a little strange, the code execution is now in line with expectations. By calling the function's bind (this), a new function that has already been associated with the existing this is returned, which means that the extra layer is wrapped for the purpose.
Because the arrow function already supports this association, it is much more refreshing to use the arrow function here, see the following example:
Copy Code code as follows:

var Pagehandler = {

ID: "123456",

Init:function () {
Document.addeventlistener ("click",
event = > this.dosomething (event.type), false);
},

Dosomething:function (type) {
Console.log ("Handling" + Type + "for" + this.id);
}
};

The event handler function in this instance calls the arrow function for This.dosomething (). The value of this is the This value in init (). Therefore it is equivalent to bind ().
The arrow function is a simple and concise feature that makes it an ideal choice for other function arguments. For example, to use a custom comparer to arrange an array on ES5, the typical code is as follows:

Copy Code code as follows:

var result = Values.sort (function (A, b) {
return a-b;
});

The above example uses a lot of syntax to implement a simple operation. If you use the arrow function, you can write very refined code:

Copy Code code as follows:

var result = Values.sort ((A, B) => a-b);

Methods such as sort/map/reduce of arrays support callback functions. Use the arrow function to simplify the writing process, freeing your hands to do what you want to do.

Third, to supplement

The arrow functions do differ from the traditional functions, but there are still common features. For example:
1. The typeof action on the arrow function returns "function".
2. The arrow function is still an instance of a function, so instanceof is executed in the same way as the traditional function.
The 3.call/apply/bind method still works with the arrow functions, but even if these methods are invoked to extend the current scope, this is still unchanged.
The most important difference between an arrow function and a traditional function is to disable the new operation.


Iv. Conclusion

The

Arrow function is a new and ECMAScript feature of 61, and is still being optimized. Use a short syntax to define a function or statement writing process is the general trend, they will blow up the sky, no one can be blocked. Its association with the keyword this makes developers less annoying and helps them improve performance through JavaScript engine optimizations. Here, the small partners of the big knife has been hungry intolerable it, if you want to try the arrow function, open the latest version of Firefox can.

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.