Modern JavaScript Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

Writing arrow functions

After reading the preceding paragraph, did you try to count how many ways there are to define a function in JS? There are actually far more than you probably think, including at least the following:

  • A named function declaration: function one(...) {...}
  • An anonymous function expression: var two = function(...) {...}
  • A named function expression: var three = function someName(...) {...}
  • An immediately-invoked expression: var four = (function() { ...; return function(...) {...}; })()
  • A function constructor: var five = new Function(...)
  • The new style, an arrow function: var six = (...) => {...}

You are probably quite used to the first trio, while the two that follow may be not so common. However, what we now care about is the last style, called an arrow function. Arrow functions work pretty much in the same fashion as functions defined in the other ways, but there are three key differences:

  • Arrow functions do not have an arguments object
  • Arrow functions may implicitly return a value, even if no return statement is provided
  • Arrow functions do not bind the value of this
In fact, there are some more differences, including the fact that you cannot use arrow functions as constructors, they don't have a prototype property, and they cannot be used as generators. For more on this, see  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.

The first difference is handled simply by using the spread operator, as we saw earlier in this chapter. So, let's focus on the last two items, which are more interesting, instead.