The arrow function is one of the most popular updates in ECMAScript 6. It introduces a new syntax to define functions using "arrow" (=>), it...it's bunkered ~. The main differences between arrow functions and traditional JavaScript functions are as follows:
1. Relevance to this. The value of this is built-in, depending on where the arrow function is defined, not the context in which the arrow function is executed.
2.new is not available. The arrow function cannot use the new keyword to instantiate the object, otherwise an error will be reported.
3.this is immutable. This is built-in to function and is a constant in the entire execution environment within the function body.
4. No arguments object. Incoming parameters cannot be accessed through the arguments object. It can only be done using explicit naming or other new ES6 features.
The existence of these differences is reasonable. First, binding to this is one of the common sources of JavaScript errors. It is easy to lose built-in values of functions or to obtain unexpected results. Secondly, limiting the arrow function to using fixed this reference is conducive to JavaScript engine optimization processing.
1. Syntax
The syntax of an arrow function is simple, defining the independent variables, then the arrow and function body. Independent variables and topics can be used in a more concise format due to different use. The following example is an arrow function that passes a parameter and returns a value.
The code copy is as follows:
var reflect = value => value;
// Equivalent to:
var reflect = function(value) {
return value;
};
It can be seen that you can just write a parameter by passing it, without adding brackets. 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 and reference.
If multiple parameters need to be passed in, brackets should be added. For example:
The code copy is as follows:
var sum = (num1, num2) => num1 + num2;
// Equivalent to:
var sum = function(num1, num2) {
return num1 + num2;
};
The sum() method is to add two parameters and pass the result back. The only difference from the previous example is that two parameters are passed in, so they must be enclosed in brackets. It is like traditional functions, with commas in parentheses separated into parameters. Similarly, if the function does not need to pass in parameters, it should also be replaced by empty brackets.
The code copy 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 execute in the function body, enclose the function body in braces and clearly define the return value. For example:
The code copy is as follows:
var sum = (num1, num2) => { return num1 + num2; }
//Equivalent to:
var sum = function(num1, num2) {
return num1 + num2;
};
The part in the braces is basically equivalent to traditional functions, except that the arguments parameter is not available.
Because braces are the logo of the body of the function. If the arrow function wants to return a custom object, it must enclose the object in brackets first. For example:
The code copy 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, the use of brackets to include curly brackets 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 inside a function. Because this takes the value according to the current execution environment of the function, it will cause misunderstandings when calling, resulting in an impact on other unrelated objects. See the following example:
The code copy 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 let the PageHandler's init() method be used to build interactions and call this.doSomething() in the click event handler function. However, the code is not executed according to the original design intention. At runtime, this points to the global object instead of the PageHandler, which causes this.doSomething() call to invalidate and an error occurs because the doSomething method does not exist in the global object.
Of course, you can use bind() in the function to explicitly associate this with PageHandler, see below:
The code copy 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);
}
};
Although it looks a bit weird, the code execution is now in line with expectations. By calling the bind(this) of the function, a new function that has been associated with the existing this is created, which means that another layer is included in order to achieve the purpose.
Because the arrow function already supports this association, it will be more refreshing to use the arrow function here. See the following example:
The code copy 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 instance calls the arrow function of this.doSomething(). The value of this is the value of this init(). Therefore, it is equivalent to bind().
The concise and concise nature of arrow functions also makes it an ideal choice for other function independent variables. For example, to use a custom comparator to arrange arrays on ES5, see the typical code below:
The code copy is as follows:
var result = values.sort(function(a, b) {
return a - b;
});
The above example uses many syntax to implement a simple operation. If you use arrow functions, you can write very refined code:
The code copy is as follows:
var result = values.sort((a, b) => a - b);
The sort/map/reduce methods of arrays support callback functions. Using arrow functions can simplify the writing process and free your hands to do what you want.
3. Supplement
Arrow functions are indeed different from traditional functions, but they still have common characteristics. For example:
1. Typeof operation on the arrow function will return "function".
2. The arrow function is still an instance of Function, so the execution method of instanceof is consistent with that of traditional functions.
3.call/apply/bind method is still applicable to arrow functions, but even if these methods are called to expand the current scope, this will not change.
The biggest difference between arrow functions and traditional functions is that new operations are disabled.
4. Conclusion
The arrow function is a new feature of ECMAScript 6 that has attracted much attention and is constantly being optimized. It is a general trend to use brief grammar to define the process of writing functions or statements, and they will surely be invincible and no one can stop them. Its association with the keyword this makes developers no longer annoyed and optimizes it to improve performance through JavaScript engine. Speaking of this, my friends are already thirsty. If you want to try the arrow function, just open the latest version of Firefox.