Summary of attention details of arrow function in javascript ES6

  • 2021-07-21 07:28:10
  • OfStack

Preface

The ES6 standard adds a new function: Arrow Function (arrow function).

Why is it called Arrow Function? Because it is defined with an arrow:


x => x * x

The arrow function above is equivalent to:


function (x) {
return x * x;
}

However, the arrow function brings some problems. Let's take a look at it.

About {}

The first question is about the arrow function and {}.

The arrow function, at first glance, seems simple to use, such as multiplying every item in an array by 2 as follows:


const numbers = [1, 2, 3];
 const result = numbers.map(n => n * 2);
 // produces [2,4,6]

However, if used improperly, it may cause unexpected problems. For example, the seemingly simple map operation of trying to produce an object literal for every item in the array still caused an accident.


const numbers = [1, 2, 3];
 const result = numbers.map(n => { value: n });
 // produces [undefined], [undefined], [undefined]

What causes it?

A little analysis shows that the above problem is that the code wrapped between curly braces in the arrow function is considered as an independent code block instead of an object literal, so when it is executed separately, the obvious result is an array all undefined.
Therefore, in this case, the code must have an explicit return statement or include the object literal in parentheses ().


const result = numbers.map(n => ({ value: n }));
 // [{value: 1}, {value:2}, {value:3}]

About this

The second question is about arrow function and this.

Using the arrow function, you can write code like this without having to temporarily store this in an extra local scope:


const adder = {
  sum: 0,
  add(numbers) {
   numbers.forEach(n => {
    this.sum += n;
   });
  }
 };
 adder.add([1, 2, 3]);
 // adder.sum === 6

However, most of the time, you may be self-righteous and make mistakes inadvertently. As the following code shows, this does not point to the "adder" object, but to the scope of the "adder" object:


const adder = {
  sum: 0,
  add: (numbers) => { // scope here is important
   numbers.forEach(n => {
    this.sum += n;
   });
  }

 };

 adder.add([1, 2, 3]);
 // adder.sum === 0

Finally, remember one point: this in the arrow function inherits from the value of the peripheral scope, so we can't change its direction.

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: