ES6 — Arrow Functions

1 Why do we have arrow functions?

In our daily development, we may need to write code similar to the following

const Person = {
    'name': 'little bear',
    'age': 18,
    'sayHello': function () {
      setInterval(function () {
        console.log('My name' + this.name + 'I am this year' + this.age + 'year old!')
      }, 1000)
    }
  }
  Person.sayHello()

  

What is the output of the above example? Maybe students who are not very familiar with javascript features (myself) will think that the output is of course
my name is little bear, and I am 18 years old this year. If your answer is this, then I want to congratulate you, wrong answer. In fact, the output of the above example is that my name is undefined, and I am undefined this year. Why does it output this result?
This is because when setInterval is executed, it is in the global scope, all this points to the global window, and there is no name and age on the window, so of course the output is undefined. Students who don't understand can go to see how this works this .
So how do we go about solving this problem?
The usual way of writing is to cache this, and then use the cached this in setInterval to operate, as follows

const Person = {
    'name': 'little bear',
    'age': 18,
    'sayHello': function () {
     let self = this
      setInterval(function () {
        console.log('my name' + self.name + 'my year' + self.age + 'year old!')
      }, 1000)
    }
  }
  const sayHelloFun = Person.sayHello
  sayHelloFun()

  

Using the above method, the output is what everyone expects. My name is little bear, and I am 18 years old.
Then, everyone may think that this is unscientific. It is obviously a method written in the object, so why use the cached object to use it correctly. The ECMA organization thinks that this is indeed a problem, and then added arrow functions to the new features of es6, which can solve this problem very well. In addition, arrow functions also use the characteristics of simplifying the amount of code.

What is an arrow function

The syntax of arrow functions is very simple, take a look at the simplest arrow function notation

() => console.log('Hello')

  


Those who haven't been exposed to arrow functions before may be surprised by the simplicity of the code. If you want to write a function like this before the comparison

function(){
    console.log('hello')
}

  

The simplicity of arrow functions is obvious at a glance.
For more information on arrow function syntax click Arrow Function Syntax

The difference between three and ordinary functions

From the above example, we can already see the advantages of arrow functions.
Compared with ordinary functions, arrow functions are mainly characterized by the following two aspects:

  1. Do not bind this, arguments
  2. Simplified code syntax

The second feature does not need to be repeated too much. Let's take a look at the two features of not binding this and arguments.

3.1 Do not bind this

What does it mean to not bind this? My personal understanding is that the this of the arrow function is actually determined when it is defined. No matter how the arrow function is called in the future, the this of the arrow function is always the this when it was defined. 
We still use the previous one. That setInterval code as an example

const Person = {
    'name': 'little bear',
    'age': 18,
    'sayHello': function () {
      setInterval(function () {
        console.log('My name' + this.name + 'I am this year' + this.age + 'year old!')
      }, 1000)
    }
Person.sayHello()

  

When Person.sayHello() executes setInterval, the this of all setInterval callback functions executed under the global action is the global object. The value of the function this in es3-5 is related to the context in which the function was called . (note the call)
we rewrite the appeal function with an arrow function

const Person = {
    'name': 'little bear',
    'age': 18,
    'sayHello': () => {
      setInterval(() => {
        console.log('My name' + this.name + 'I am this year' + this.age + 'year old!')
      }, 1000)
    }
Person.sayHello()

  

Guess what is the result? ? ?
The output is that my name is 'little bear', am I 18 years old?
Haha, it's so naive, I thought the same at first, but after outputting it later, I found that the result was wrong, and the output was still undefined. why? ?
Because I write the method in the object, and the parentheses of the object cannot enclose the scope. So at this time this still points to the global object.
Therefore, the above errors can remind us that it is best not to use arrow functions as methods of objects.
We need to give another example, as follows

function Person () {
  this.name = 'little bear',
  this.age = 18
  let self = this
  setInterval(function sayHello () {
    console.log('my name' + self.name + 'my year' + self.age + 'year old!')
  }, 1000)
}
let p = new Person()

  

Cache this, and then output, we can achieve the result we want.
Change the above example to the form of an arrow function as follows

function Person () {
  this.name = 'little bear',
  this.age = 18
  setInterval(() => {
    console.log('My name' + this.name + 'I am this year' + this.age + 'year old')
},1000)
}
let p = new Person()

  

We can see that the arrow function uses this of the context in which it was defined, regardless of where it was called.

3.2 Not binding arguments

Another feature of arrow functions is that they do not bind arguments, that is, if you use the arguments parameter in an arrow function, you cannot get what you want.

let arrowfunc = () => console.log(arguments.length)
arrowfunc()
//output
arguments is not defined

  

So we can't use the arguments object directly in the arrow function, but what if we want to get the parameters of the function?
We can use the rest parameters instead of arguments rest parameter details

let arrowfunc = (...theArgs) => console.log(theArgs.length)
arrowfunc(1,2)
//output
2

  

Four when not to use arrow functions

Earlier we have seen a lot about the benefits of es6 arrow functions, but also some of the shortcomings of arrow functions. So when should we use arrow functions and when should we not use them?
1. The method as an object
When writing the example of this blog, because my level is indeed limited, it led to the error in the beginning of the article. However, I also want to tell you that it is best not to use arrow functions in object methods, which may cause some problems. Unless you are familiar with arrow functions.
2. It cannot be used as a constructor.
Due to the fact that the this of arrow functions is not bound, arrow functions cannot be used as constructors. In fact, if this is done, an error will be reported.
3. Define the prototype method

function Person (name){
this.name = name
}
Person.prototype.sayHello = () => {
    console.log(this)
}
var p1 = new Person ()
p1.sayHello()
//output
window object

  

Here this points to the window object, which is a bit like defining it in the object method

Five Summary

Arrow functions are most suitable for use in non-method functions due to the simplicity of their code and the characteristics of not binding the caller's this. When used in method functions, special attention should be paid to its this binding. If dynamic Modify this, it is best not to use arrow functions. So there is never one solution that can solve everything, only suitable application scenarios.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325890255&siteId=291194637