Arrow Functions

ES6 offers some new syntax for dealing with this: "arrow functions".Arrow functions also make higher order functions much easier to work with.

The new "fat arrow" notation can be used to define anonymous functions in a simpler way.

Consider the following example:

  1. items.forEach(function(x) {
  2. console.log(x);
  3. incrementedItems.push(x+1);
  4. });

This can be rewritten as an "arrow function" using the following syntax:

  1. items.forEach((x) => {
  2. console.log(x);
  3. incrementedItems.push(x+1);
  4. });

Functions that calculate a single expression and return its values can be defined even simpler:

  1. incrementedItems = items.map((x) => x+1);

The latter is almost equivalent to the following:

  1. incrementedItems = items.map(function (x) {
  2. return x+1;
  3. });

There is one important difference, however: arrow functions do not set a local copy of this, arguments, super, or new.target. When this is used inside an arrow function JavaScript uses the this from the outer scope. Consider the following example:

  1. class Toppings {
  2. constructor(toppings) {
  3. this.toppings = Array.isArray(toppings) ? toppings : [];
  4. }
  5. outputList() {
  6. this.toppings.forEach(function(topping, i) {
  7. console.log(topping, i + '/' + this.toppings.length); // `this` will be undefined
  8. });
  9. }
  10. }
  11. var myToppings = new Toppings(['cheese', 'lettuce']);
  12. myToppings.outputList();

Let's try this code on http://jsbin.com. As we see, this gives us an error, since this is undefined inside the anonymous function.

Now, let's change the method to use the arrow function:

  1. class Toppings {
  2. constructor(toppings) {
  3. this.toppings = Array.isArray(toppings) ? toppings : [];
  4. }
  5. outputList() {
  6. this.toppings.forEach((topping, i) => {
  7. console.log(topping, i + '/' + this.toppings.length) // `this` works!
  8. });
  9. }
  10. }
  11. var myToppings = new Toppings(['cheese', 'lettuce']);
  12. myToppings.outputList();

Let's try this code on http://jsbin.com. Here this inside the arrow function refers to the instance variable.

Warning arrow functions do not have their own arguments variable, whichcan be confusing to veteran JavaScript programmers. super and new.targetare also scoped from the outer enclosure.

原文: https://angular-2-training-book.rangle.io/handout/features/arrow_functions.html