Home  >  Article  >  Web Front-end  >  Detailed introduction to the new feature Arrow Function of ECMAScript6_Basic knowledge

Detailed introduction to the new feature Arrow Function of ECMAScript6_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 16:45:331491browse

Arrow functions are one of the most talked about updates in ECMAScript 6. It introduces a new syntax for defining functions using "arrows" (=>), which... it's amazing. The main differences between arrow functions and traditional JavaScript functions are the following points:
1. The association with this. The value of this inside a function depends on where the arrow function is defined, not the context in which the arrow function is executed.
2.new is not available. Arrow functions cannot use the new keyword to instantiate objects, otherwise an error will be reported.
3.this is immutable. The built-in this of the function is immutable and is constant throughout the entire execution environment of the function body.
4. There is no arguments object. Incoming parameters cannot be accessed through the arguments object. This can only be done using explicit naming or other new ES6 features.

These differences are justified. First, binding to this is one of the common sources of JavaScript errors. It is easy to lose the value of the built-in function, or get unexpected results. Secondly, limiting arrow functions to using fixed this references is beneficial to JavaScript engine optimization.

1. Grammar

The syntax of the arrow function is very simple, define the independent variable, then the arrow and the function body. The independent variables and topics may be in a more concise format depending on their usage. The following example uses an arrow function that passes one parameter and returns a value.

Copy code The code is as follows:

var reflect = value => value;
// Equivalent to:

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

As you can see, if you pass a parameter, just write it directly without adding parentheses. The arrow points to the function body, but the function body is just a simple return statement, so there is no need to add braces. After the function is constructed, it is assigned to reflect for reference.
If you need to pass in multiple parameters, you should add parentheses. For example:

Copy code The code is as follows:

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

The sum() method adds two parameters and returns the result. The only difference from the previous example is that two parameters are passed in, so they are enclosed in parentheses. It is the same as a traditional function, with commas separating the parameters passed in the parentheses. Similarly, if the function does not require parameters, empty parentheses should be used instead.

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

If you want to use a standard function body, or there may be more statements to be executed in the function body, enclose the function body in curly brackets and clearly define the return value. For example:

Copy code The code is as follows:

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

The part inside the curly brackets is basically equivalent to the traditional function, except that the arguments parameter is not available.
Because the curly braces are the symbols of the function body. If the arrow function wants to return a custom object, the object must be enclosed in parentheses. For example:

Copy code The code is as follows:

var getTempItem = id = > ({
id: id,
name: "Temp"
});
// Equivalent to:
var getTempItem = function(id) {
return {
id: id,
name: "Temp"
};
};

As can be seen from the above example, using parentheses to include curly braces is the definition of the object, not the body of the function.

2. Use

One of the most common errors in JavaScript is this association within functions. Because this takes the value based on the current execution environment of the function, misunderstandings will occur during the call, which will affect other unrelated objects. See the example below:

Copy code The code is 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, the original intention is to use the init() method of PageHandler to build interactions and call this.doSomething() in the click event handling function. However, the code was not executed according to the original design intention. At runtime, this pointed to the global object instead of the PageHandler, causing the this.doSomething() call to be invalid and an error being reported because the doSomething method does not exist in the global object.
Of course, you can use bind() in the function to clearly associate this with the PageHandler, see below:

Copy code The code is 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); expected. By calling bind(this) of the function, a new function return is created that is associated with the existing this, which means that an additional layer is wrapped to achieve the purpose.
Because the arrow function already supports this association, it is more convenient to use the arrow function here. See the following example:



Copy code
The code is 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 handling function in this example calls the arrow function of this.doSomething(). The value of this is the this value in init(). Therefore it is equivalent to bind().
The concise and concise nature of the arrow function also makes it an ideal choice for arguments of other functions. For example, to use a custom comparator to sort an array on ES5, the typical code is as follows:


Copy the code

The code is 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 arrow functions, you can write very concise code:

Copy the code

The code is as follows:var result = values.sort((a, b) => a - b);

Array sort/map/reduce and other methods all support callback functions. Using arrow functions can simplify the writing process and free your hands to do what you want to do.

3. Supplement

Arrow functions are indeed different from traditional functions, but they still have common characteristics. For example:
1. Typeof operation on arrow function will return "function".
2. The arrow function is still an instance of Function, so the execution method of instanceof is consistent with the traditional function.
3. The call/apply/bind method is still applicable to arrow functions, but even if these methods are called to expand the current scope, this will still not change.
The biggest difference between arrow functions and traditional functions is that the new operation is disabled.


4. Conclusion

Arrow function is a new feature of ECMAScript 6 that has attracted much attention, and it is still being optimized. Using short syntax to define functions or statements to write processes is the general trend. They are bound to explode and no one can stop them. Its association with the keyword this relieves developers and helps improve performance through JavaScript engine optimization. Having said that, friends are already thirsty for their swords. If you want to try the arrow function, just open the latest version of Firefox.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn