This is the 8th day of my participation in the August More Text Challenge. For details, see:August is more challenging
Arrow function
In ES6, the arrow function is added. Compared with the traditional function, the arrow function is more concise and convenient in writing, and the arrow function is improved in this aspect. Today we will look at the arrow function in ES6 and the arrow function in thisCopy the code
The arrow function
A function in JS consists of the function keyword, the params argument, and the body wrapped in curly braces. To distinguish a function from a normal function, we call it a normal function. A normal function can be written declarative or assigned:
Let testB = function(b){console.log(b)} testB(' I am b ') {console.log(b)} testB(' I am b ')Copy the code
After watching the normal function of writing, we take a look at the arrow function method and define the arrow function grammar more concise than the conventional function, allows you to use the arrow in the ES6 = > to define the function, the arrow arrow function saves the function keyword, the parameters of the function on = > parentheses, in front of the body of the function behind = > curly braces, Now, let’s look at how the arrow function is written,
// let testB = function(MSG){console.log(MSG)} testB(' I am a regular function ') // Let testB = (MSG)=>{console.log(MSG)} TestB (' I am the arrow function ')Copy the code
This comparison shows that the arrow function is simpler and more convenient to write than the regular function, but there are some rules in the arrow function writing, let me take a look at it, let’s look at the arrow function parameters and the body of the function
Arguments to the arrow function
- If the arrow function has no arguments, just write an empty parenthesis
Let fun1 = () => {console.log(' I have no arguments '); };Copy the code
- If the arrow function has only one argument, you can omit the parentheses surrounding the arguments. If there are multiple arguments, parentheses are required, and each argument is separated by a comma
// Let fun1 = MSG => {console.log(MSG); }; Let fun1 = (MSG,msg1,msg2) => {console.log(MSG,msg1,msg2); }; Fun2 (' I am ',' with ',' multiple arguments ')Copy the code
The body of the arrow function
- If the body of an arrow function has only one line of code that simply returns a variable or a simple JS expression, you can omit the braces {} and return. If the body of an arrow function has no {}, it will return for you. For example:
Let sum = function(num1, num2) {return num1 + num2; }; // Return variable let fun = val => val; Let sum = (num1, num2) => num1 + num2;Copy the code
- If the body of the arrow function had only one line of code that returned an object, it could be written like this:
Let item = id => ({id: id, name: "Temp"}); Let item = id => {id: id, name: "Temp"}; The reason is that the braces of the object are resolved by the arrow function to the braces of the function body, so an error is reportedCopy the code
- If the body of the arrow function has only one statement and does not require a return value (the most common is to call a function), you can precede the statement with the void keyword
let fun = () => void noRerurn();
Copy the code
The difference between the arrow function and the regular function
So if you look at the way the arrow function is written up here, you can see that the arrow function is a little bit more concise and clear than the normal function, so it’s a little bit less convenient to read the code, so let me go ahead and look at the differences between the arrow function and the normal function
Arrow functions have no prototype property
Let a = () => {}; console.log(a.prototype); Function a() {}; console.log(a.prototype); / / {constructor: f}.Copy the code
The arrow function this points to different things
In a regular function, this refers to the object that called it. If used as a constructor, this refers to the object instance being created. The arrow function itself does not have this. The arrow function’s this point is defined by inherits this from the first outer function. Therefore, the this point in the arrow function is defined at the time it is defined and never changes thereafter
Note: this in the arrow function is pointed to at definition, not at call!!
let obj = {
a: 10,
b: () => {
console.log(this.a); // undefined
console.log(this);
// Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
},
c: function() {
console.log(this.a); // 10
console.log(this); // {a: 10, b: ƒ, c: ƒ}
}
}
obj.b();
obj.c();
Copy the code
Call | apply | bind cannot change the arrow point of this function
Call | apply | the bind method can be used to modify the function executes this point, but this arrow function is defined in when it was pointing to, and is never change, so the method cannot modify the arrow function of this point
let name = 'Kobe Bryant';
let fun = () => {
console.log(this.name)
};
fun(); // Toney
fun.call({ name: 'James' }); // Kobe Bryant
fun.apply({ name: 'Wade' }); // Kobe Bryant
fun.bind({ name: 'Jordan' })(); // Kobe Bryant
Copy the code
Arrow functions cannot be used as constructors
The constructor uses the new keyword to generate an object instance. The process of generating an object instance is also the process of binding this to the instance through the constructor. The arrow function does not have its own this. To create an object, new first creates an empty object and points its __proto__ to the constructor’s prototype, inheriting the method on the prototype, but the arrow function has no prototype. So you can’t use an arrow as a constructor, and you can’t call an arrow function through the new operator
let People = (name, age) => { this.name = name; this.age = age; }; let p = new People('Kobe Bryant', 41); // 错 误 People is not a constructorCopy the code
There is no arguments in the arrow function
Argument is a keyword in JavaScript that points to all the arguments passed in by the caller. In the arrow function, if you want to get all the parameters passed in, you need to use the REST parameter (… Variable name)
Function A(A){console.log(arguments); } A,2,3,4,5,8 (1); // [1, 2, 3, 4, 5, 8, callee: ƒ, Symbol(symbol.iterator): ƒ] // Let B = (B)=>{console.log(arguments); },92,32,32 (2 B); // Uncaught ReferenceError: Arguments are not defined // rest parameter... let C = (... c) => { console.log(c); } C (3,82,32,11323); // [3, 82, 32, 11323]Copy the code
Arrow functions cannot be treated as Generator functions, and the yield keyword cannot be used
Arrow function considerations and applicable and inapplicable scenarios
Matters needing attention
- An arrow function is a statement that returns an object literal, enclosed in parentheses
- Arrow functions cannot wrap lines between arguments and arrows
- Arrow function resolution order relative | |
- The arrow function points to this when it is defined, not when it is called
- If the “this” of the outer normal function changes, the “this” of the arrow function will change
Applicable scenario
- A simple function expression that returns a unique value. There is no reference to this inside the function
- When an internal function needs to call this from an external function using bind.
- When an argument to a function requires an array method
Inapplicable Scenarios
- Execute more statements, use recursion, refer to function names, and bind and unbind events.
- This unexpected pointing of the arrow function and readability of the code
conclusion
About the arrow function of ES6, I summed up here is not quite complete, if there is a mistake I hope you big guy to give me some advice, but also hope that this article can help some students learn something, if the feeling is good, can give a thumbs up, also welcome everyone to comment area discussion and discussion, thank you