Preface
The ES6 standard has added a new function: Arrow Function.
Why is it called Arrow Function? Because it is defined by an arrow:
x => x * x
The above arrow function is equivalent to:
function (x) { return x * x; }
But the arrow function brings some problems, let’s take a look together.
about{}
The first question is about arrow functions and {}.
The arrow function, at first glance, seems simple to use, for example, multiplying each item in the array by 2:
const numbers = [1, 2, 3]; const result = (n => n * 2); // produces [2,4,6]
However, if used improperly, unexpected problems may arise. For example, the following is trying to generate object literals for each item in the array. The map operation that looks quite simple still caused an accident.
const numbers = [1, 2, 3]; const result = (n => { value: n }); // produces [undefined], [undefined], [undefined]
What causes it?
A little analysis shows that the above problem is that the code wrapped in braces inside the arrow function is considered an independent code block rather than an object literal. Therefore, if it is executed separately, the result is obviously an array that is completely undefined.
Therefore, in this case, the code in it must have a clear return statement or include the object literal in parentheses ().
const result = (n => ({ value: n })); // [{value: 1}, {value:2}, {value:3}]
About this
The second question is about arrow functions and this.
Using arrow functions, you can write code like this without having to temporarily store this in the local scope:
const adder = { sum: 0, add(numbers) { (n => { += n; }); } }; ([1, 2, 3]); // === 6
However, many times, you may write it inadvertently incorrectly. As shown in the following code, this does not point to the "adder" object, but to the scope where the "adder" object is located:
const adder = { sum: 0, add: (numbers) => { // scope here is important (n => { += n; }); } }; ([1, 2, 3]); // === 0
Finally, remember one thing: this in the arrow function inherits from the value of the peripheral scope, so we cannot change its pointing.
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.