----Arrow functions----

Arrow functions

Arrow functions表达式相比函数表达式有更短的语法,没有自己的this、argument、super或者new.target。

1.语法规则:

基础语法:

  (param1, param2, …, paramN) => { statements }

  (param1, param2, …, paramN) => expression

  // equivalent to: => { return expression; }

 

  // Parentheses are optional when there's only one parameter name:

  (singleParam) => { statements }

  singleParam => { statements }

 

  // The parameter list for a function with no parameters should be written with a pair of parentheses.

  () => { statements }

高级语法:

  // Parenthesize the body of function to return an object literal expression:

  params => ({foo: bar})

 

  // Rest parameters and default parameters are supported

  (param1, param2, ...rest) => { statements }

  (param1 = defaultValue1, param2, …, paramN = defaultValueN) => {

  statements }

 

  // Destructuring within the parameter list is also supported

  var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;

  f(); // 6

2.箭头函数用作方法

箭头函数表达式最适合非方法函数

Eg:

  'use strict';

 

  var obj = {

    i: 10,

    b: () => console.log(this.i, this),

    c: function() {

      console.log(this.i, this);

    }

  }

 

  obj.b(); // prints undefined, Window {...} (or the global object)

  obj.c(); // prints 10, Object {...}

3.功能体

箭头功能可以具有“简洁的身体”或通常的“块体”。

在简洁的主体中,只指定了一个表达式,该表达式成为显式返回值。在块体中,您必须使用显式return语句。

Eg:

  var func = x => x * x;                 

  // concise body syntax, implied "return"

 

  var func = (x, y) => { return x + y; };

  // with block body, explicit "return" needed

虽然箭头函数中的箭头不是运算符,但箭头函数具有特殊的解析规则,与常规函数相比,它们与运算符优先级的交互方式不同。

  let callback;

   

  callback = callback || function() {}; // ok

 

  callback = callback || () => {};     

  // SyntaxError: invalid arrow-function arguments

 

  callback = callback || (() => {});    // ok

原文地址:https://www.cnblogs.com/player-yenney/p/9986087.html