Understand the use of arrow functions

Write an article for the first time, write bad please give directions and understand

Some new features have been updated in ES6, including the arrow function. The use of ES6 can improve the use of our functions and simplify our code more efficiently. Let’s look at an example

>`function sum(){ return a+1 }`
console.log(sum(10))
Copy the code

The above function is a defined summation function, which takes four lines of code. In practice, we will use more. Here is the simplified code:

Const sum = (a, b) => {return a+b} console.log(sum(1,4))Copy the code

The above code simplifies one line, but it is a simplification, and the more code there is, the more simplification there is

Arrow function this

In the following code snippet, our function defines a Person object function

const person={` name: "tom", sayHi: function() { console.log(`hi,my name is ${this.name}`)}Copy the code

Inside the sayHi function, there is an anonymous sayHi function. When we define sayHi with the arrow function, there is a this inside the sayHi function. The name attribute of person cannot be called, as follows:

const person = {
      name: "tom".sayHi: () = > {
        console.log(`hi,my name is The ${this.name}`)}}; person.sayHi()Copy the code

Now let’s solve this problem

sayHi: function () {
        
        setTimeout(() = > {
          console.log(`hi,my name is The ${this.name}`)},1000);
      }
    }
    
    person.sayHi()
Copy the code

So now that we’ve solved this problem, this problem tells us that when we have a problem like this, we can solve it this way by setting up a function