[ES6] arrow function

Posted by eektech909 on Fri, 25 Feb 2022 11:53:06 +0100

1, What is the arrow function?

ES6 allows functions to be defined using "arrows" (= >).

let foo = v => v; 

// The arrow function above is equivalent to:

let foo = function(v) {
 return v; }; 

The left side of the arrow function (= >) is the parameter and the right side is the function body.

2, Detailed usage

1. Parameters of arrow function

When the arrow function does not require parameters or multiple parameters, a parenthesis is used to represent the parameter part. When there is only one parameter, parentheses can not be written.

let foo = () => 5;
// Equivalent to
let foo = function () { return 5 };

// One parameter
let x = x => x

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

2. Function body of arrow function

When there is more than one statement in the code block of the arrow function, it is necessary to enclose them in braces and return them with the return statement.

var sum = (num1, num2) => { return num1 + num2; } 

Since braces are interpreted as code blocks, if the arrow function directly returns an object, you must add parentheses outside the object, otherwise an error will be reported.

// report errors
let getTempItem = id => { id: id, name: "Temp" };
// No error reporting
let getTempItem = id => ({ id: id, name: "Temp" });

When the arrow function has only one line of statement and does not need to return a value, you can use the following writing method, so you don't need to write braces.

let fn = () => void doesNotReturn(); 

Arrow functions can be used in conjunction with variable deconstruction.

const full = ({ first, last }) => first + ' ' + last;
// Equivalent to
function full(person) {
 return person.first + ' ' + person.last; } 

The arrow function makes the expression more concise.

const isEven = n => n % 2 == 0;
const square = n => n * n; 

The above code only uses two lines to define two simple tool functions. If the arrow function is not used, it may occupy multiple lines, and it is not as eye-catching as it is now. One use of the arrow function is to simplify the callback function.

3. Arrow function and ordinary function

Variable promotion

Function declaration method of ES5 (there are variables and function definition promotion):

//Formally, it can be used first and then defined.
console.log(sum)
function sum(x, y) {
    return x + y
}

In ES6, there is no variable promotion for functions defined in let mode:

// report errors
console.log(sum)
let sum = function(x, y){
    return x + y
}

The direction of this

In ordinary functions, this points to the object at the time of call

let oBtn = document.querySelector('#btn')
oBtn.addEventListener('click', function () {
     setTimeout(function () {
         console.log(this)
     }, 1000)
  
})
// The result points to the Window object. Because setTimeout is Window Short for settimeout(), the object calling it is Window
let oBtn = document.querySelector('#btn')
oBtn.addEventListener('click', function () {
     // console.log(this)
     // This refers to the object that calls this function. The object that calls bind() is the oBtn object. Bind this to the setTimeout function and output it
     setTimeout(function () {
     // call apply bind
         console.log(this)
     //bind() will not execute immediately, but wait until 1s later, while call and apply will execute immediately
     }.bind(this), 1000)
  
})
// The result points to the oBtn object

In the arrow function, this points to the object at the time of definition.

let oBtn = document.querySelector('#btn')
oBtn.addEventListener('click', function () {
    setTimeout(() => {
        console.log(this)
    }, 1000)
})
// The result points to the oBtn object

In fact, the arrow function itself does not have this, but inherits the this of the execution context of the outer layer

Arrow functions cannot be used as constructors

//No error reporting
function People(name, age){
    console.log(this)
    this.name = name
    this.age = age
}
let p1 = new People('Dorothy', 20)
console.log(p1)


//report errors
let People = (name, age) => {
    this.name = name
    this.age = age
}
let p1 = new People('Dorothy', 20)
console.log(p1)

arguments object is not allowed

//report errors
let foo = () => {
    console.log(arguments)
}
foo(1, 2, 3)

You can use the rest parameter instead of the arguments object

//No error reporting
let foo = (...args) => {
    // console.log(arguments)
    console.log(args)
}
foo(1, 2, 3)
//[1, 2, 3]

summary

There are several points for attention in the use of arrow functions.
(1) The this object in the function body is the object where it is defined, not the object where it is used.
(2) It cannot be used as a constructor, that is, it cannot use the new command, otherwise an error will be thrown.
(3) You cannot use the arguments object, which does not exist in the function body. If you want to use, you can use the rest parameter instead.
(4) You cannot use the yield command, so the arrow function cannot be used as a Generator function.

The direction of this object is variable, but it is fixed in the arrow function.

Topics: Javascript ECMAScript