This is the ninth day of my participation in the August More text Challenge. For details, see: August More Text Challenge
What is the arrow function
The arrow function is a new syntax for defining function expressions in Es6. It simplifies the way we wrote functions earlier. The function object instantiated by the arrow function behaves the same as the function expression we created earlier in Es5. Arrow functions can be used anywhere a function expression is used. However, there are some differences between the arrow function and the traditional way of writing, which we will explain below.
The way arrow functions are written
//Es5
let sum = function(a,b){
return a + b;
}
// Es6
let sum1 = (a,b) = >{
return a + b;
}
console.log(sum(1.2));/ / 3
console.log(sum1(1.2));/ / 3
Copy the code
You can see that we’re missing function, if we just pass one argument we can get rid of the parentheses, we can just say let sum1 = a =>{} or we can run it, but it’s not recommended to do that, let’s just write the parentheses, just to make it more readable.
Parameters in the arrow function
The arrow function cannot be accessed using the keyword Arguments and can only be accessed through the named arguments defined.
Arguments is an array-like object corresponding to the arguments passed to the function. If you look at our example, the index zero is the first parameter we pass in.
function sum(){
console.log(arguments[0]);
}
sum(3);/ / 3
let sum1 = () = > {
console.log(arguments[0]);
}
sum1(3);Uncaught ReferenceError: Arguments are not defined
Copy the code
This in the arrow function
In Es5, this reference refers to a function as a context object for a method call, and we all know that this calls to Windows globally in the web page. If the function is a method on an object, its this pointer points to that object. But in an arrow function, the arrow function doesn’t create its own this, it just inherits this from the previous level of its scope chain.
function o() {
this.royaltyName = 'Jackons';
// this refers to an instance of King
setTimeout( () => console.log(this.royaltyName), 1000);
};
function j() {
this.royaltyName = 'bear';
// this refers to the window object
setTimeout(function () {
console.log(this.royaltyName);
}, 1000);
}
new o(); //jackson
new j(); //undefinde
Copy the code
Note: The function arrow cannot use arguments, super, and new.target. It cannot be used as a constructor. It also has no Prototype property
Arrow functions have their advantages, but they also have their disadvantages. The advantage of arrow functions is that the code is concise. This is defined in advance, but their disadvantages are also the same.
- Define functions on objects
- Define the function on the prototype
- Callback functions in dynamic context
- Constructor
- A function that is too short