箭头函数

2018-10-18  本文已影响9人  天字一等

定义:<article id="wikiArticle" style="font-style: normal !important; display: block; margin: 0px; padding: 0px 0px 20px; border-width: 0px 0px 3px; border-top-style: initial; border-right-style: initial; border-left-style: initial; border-top-color: initial; border-right-color: initial; border-left-color: initial; border-image: initial; position: relative; border-bottom-style: solid; border-bottom-color: rgb(61, 126, 154);">

语法

基础语法

(参数1, 参数2, …, 参数N) => { 函数声明 }
(参数1, 参数2, …, 参数N) => 表达式(单一)
//相当于:(参数1, 参数2, …, 参数N) =>{ return 表达式; }

// 当只有一个参数时,圆括号是可选的:
(单一参数) => {函数声明}
单一参数 => {函数声明}

// 没有参数的函数应该写成一对圆括号。
() => {函数声明}

高级语法

//加括号的函数体返回对象字面表达式:
参数=> ({foo: bar})

//支持剩余参数和默认参数
(参数1, 参数2, ...rest) => {函数声明}
(参数1 = 默认值1,参数2, …, 参数N = 默认值N) => {函数声明}

//同样支持参数列表解构
let f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f();  // 6

描述

参考 "ES6 In Depth: Arrow functions" on hacks.mozilla.org.

引入箭头函数有两个方面的作用:更简短的函数并且不绑定this

更短的函数

var materials = [
  'Hydrogen',
  'Helium',
  'Lithium',
  'Beryllium'
];

materials.map(function(material) { 
  return material.length; 
}); // [8, 6, 7, 9]

materials.map((material) => {
  return material.length;
}); // [8, 6, 7, 9]

materials.map(material => material.length); // [8, 6, 7, 9]

不绑定this

在箭头函数出现之前,每个新定义的函数都有它自己的 [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)值(在构造函数的情况下是一个新对象,在严格模式的函数调用中为 undefined,如果该函数被作为“对象方法”调用则为基础对象等)。This被证明是令人厌烦的面向对象风格的编程。

function Person() {
  // Person() 构造函数定义 `this`作为它自己的实例.
  this.age = 0;

  setInterval(function growUp() {
    // 在非严格模式, growUp()函数定义 `this`作为全局对象, 
    // 与在 Person()构造函数中定义的 `this`并不相同.
    this.age++;
  }, 1000);
}

var p = new Person();

在ECMAScript 3/5中,通过将this值分配给封闭的变量,可以解决this问题。

function Person() {
  var that = this;
  that.age = 0;

  setInterval(function growUp() {
    //  回调引用的是`that`变量, 其值是预期的对象. 
    that.age++;
  }, 1000);
}

或者,可以创建绑定函数,以便将预先分配的this值传递到绑定的目标函数(上述示例中的growUp()函数)。

箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。因此,在下面的代码中,传递给setInterval的函数内的this与封闭函数中的this值相同:

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| 正确地指向person 对象
  }, 1000);
}

var p = new Person();

与严格模式的关系

鉴于 this 是词法层面上的,严格模式中与 this 相关的规则都将被忽略。

function Person() {
  this.age = 0;
  var closure = "123"
  setInterval(function growUp() {
    this.age++;
    console.log(closure)
  }, 1000);
}

var p = new Person();

function PersonX() {
  'use strict'
  this.age = 0;
  var closure = "123"
  setInterval(()=>{
    this.age++;
    console.log(closure)
  }, 1000);
}

var px = new PersonX();

严格模式的其他规则依然不变.

通过 call 或 apply 调用

由于 箭头函数没有自己的this指针,通过 call()* 或* apply() 方法调用一个函数时,只能传递参数(不能绑定this---译者注),他们的第一个参数会被忽略。(这种现象对于bind方法同样成立---译者注)

var adder = {
  base : 1,

  add : function(a) {
    var f = v => v + this.base;
    return f(a);
  },

  addThruCall: function(a) {
    var f = v => v + this.base;
    var b = {
      base : 2
    };

    return f.call(b, a);
  }
};

console.log(adder.add(1));         // 输出 2
console.log(adder.addThruCall(1)); // 仍然输出 2(而不是3 ——译者注)

不绑定arguments

箭头函数不绑定Arguments 对象。因此,在本示例中,arguments只是引用了封闭作用域内的arguments:

var arguments = [1, 2, 3];
var arr = () => arguments[0];

arr(); // 1

function foo(n) {
  var f = () => arguments[0] + n; // 隐式绑定 foo 函数的 arguments 对象. arguments[0] 是 n
  return f();
}

foo(1); // 2

在大多数情况下,使用剩余参数是相较使用arguments对象的更好选择。

function foo() { 
  var f = (...args) => args[0]; 
  return f(2); 
}

foo(1); 
// 2

像函数一样使用箭头函数

如上所述,箭头函数表达式对非方法函数是最合适的。让我们看看当我们试着把它们作为方法时发生了什么。

'use strict';
var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log( this.i, this)
  }
}
obj.b(); 
// undefined
obj.c(); 
// 10, Object {...}

箭头函数没有定义this绑定。另一个涉及Object.defineProperty()的示例:

'use strict';
var obj = {
  a: 10
};

Object.defineProperty(obj, "b", {
  get: () => {
    console.log(this.a, typeof this.a, this);
    return this.a+10; 
   // 代表全局对象 'Window', 因此 'this.a' 返回 'undefined'
  }
});

使用 new 操作符

箭头函数不能用作构造器,和 new一起用会抛出错误。

var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor

使用prototype属性

箭头函数没有prototype属性。

var Foo = () => {};
console.log(Foo.prototype); // undefined

使用 yield 关键字

[yield](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield) 关键字通常不能在箭头函数中使用(除非是嵌套在允许使用的函数内)。因此,箭头函数不能用作生成器。

函数体

箭头函数可以有一个“简写体”或常见的“块体”。

在一个简写体中,只需要一个表达式,并附加一个隐式的返回值。在块体中,必须使用明确的return语句。

var func = x => x * x;                  
// 简写函数 省略return

var func = (x, y) => { return x + y; }; 
//常规编写 明确的返回值

返回对象字面量

记住用params => {object:literal}这种简单的语法返回对象字面量是行不通的。

var func = () => { foo: 1 };               
// Calling func() returns undefined!

var func = () => { foo: function() {} };   
// SyntaxError: function statement requires a name

这是因为花括号({} )里面的代码被解析为一系列语句(即 foo 被认为是一个标签,而非对象字面量的组成部分)。

所以,记得用圆括号把对象字面量包起来:

var func = () => ({foo: 1});

换行

箭头函数在参数和箭头之间不能换行。

var func = ()
           => 1; 
// SyntaxError: expected expression, got '=>'

解析顺序

虽然箭头函数中的箭头不是运算符,但箭头函数具有与常规函数不同的特殊运算符优先级解析规则。

let callback;

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

callback = callback || () => {};      
// SyntaxError: invalid arrow-function arguments

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

更多示例

// 空的箭头函数返回 undefined
let empty = () => {};

(() => 'foobar')(); 
// Returns "foobar"
// (这是一个立即执行函数表达式,可参阅 'IIFE'术语表) 

var simple = a => a > 15 ? 15 : a; 
simple(16); // 15
simple(10); // 10

let max = (a, b) => a > b ? a : b;

// Easy array filtering, mapping, ...

var arr = [5, 6, 13, 0, 1, 18, 23];

var sum = arr.reduce((a, b) => a + b);  
// 66

var even = arr.filter(v => v % 2 == 0); 
// [6, 0, 18]

var double = arr.map(v => v * 2);       
// [10, 12, 26, 0, 2, 36, 46]

// 更简明的promise链
promise.then(a => {
  // ...
}).then(b => {
  // ...
});

// 无参数箭头函数在视觉上容易分析
setTimeout( () => {
  console.log('I happen sooner');
  setTimeout( () => {
    // deeper code
    console.log('I happen later');
  }, 1);
}, 1);

箭头函数也可以使用条件(三元)运算符:

var simple = a => a > 15 ? 15 : a;
simple(16); // 15
simple(10); // 10

let max = (a, b) => a > b ? a : b;

箭头函数内定义的变量及其作用域

// 常规写法
var greeting = () => {let now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
greeting();          //"Good day."
console.log(now);    // ReferenceError: now is not defined 标准的let作用域

// 参数括号内定义的变量是局部变量(默认参数)
var greeting = (now=new Date()) => "Good" + (now.getHours() > 17 ? " evening." : " day.");
greeting();          //"Good day."
console.log(now);    // ReferenceError: now is not defined

// 对比:函数体内{}不使用var定义的变量是全局变量
var greeting = () => {now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
greeting();           //"Good day."
console.log(now);     // Fri Dec 22 2017 10:01:00 GMT+0800 (中国标准时间)

// 对比:函数体内{} 用var定义的变量是局部变量
var greeting = () => {var now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));}
greeting(); //"Good day."
console.log(now);    // ReferenceError: now is not defined

箭头函数也可以使用闭包:

// 标准的闭包函数
function A(){
      var i=0;
      return function b(){
              return (++i);
      };
};

var v=A();
v();    //1
v();    //2

//箭头函数体的闭包( i=0 是默认参数)
var Add = (i=0) => {return (() => (++i) )};
var v = Add();
v();           //1
v();           //2

//因为仅有一个返回,return 及括号()也可以省略
var Add = (i=0)=> ()=> (++i);

箭头函数递归

var fact = (x) => ( x==0 ?  1 : x*fact(x-1) );
fact(5);       // 120

规范

| Specification | Status | Comment |
| ECMAScript 2015 (6th Edition, ECMA-262)
<small lang="zh-CN" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px;">Arrow Function Definitions</small>
| Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262)
<small lang="zh-CN" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px;">Arrow Function Definitions</small>
| Draft | |

浏览器兼容

Update compatibility data on GitHub

<abbr class="only-icon" title="Desktop" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Desktop</abbr> <abbr class="only-icon" title="Mobile" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Mobile</abbr> <abbr class="only-icon" title="Server" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Server</abbr>
<abbr class="only-icon" title="Chrome" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Chrome</abbr> <abbr class="only-icon" title="Edge" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Edge</abbr> <abbr class="only-icon" title="Firefox" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Firefox</abbr> <abbr class="only-icon" title="Internet Explorer" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Internet Explorer</abbr> <abbr class="only-icon" title="Opera" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Opera</abbr> <abbr class="only-icon" title="Safari" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Safari</abbr> <abbr class="only-icon" title="Android webview" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Android webview</abbr> <abbr class="only-icon" title="Chrome for Android" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Chrome for Android</abbr> <abbr class="only-icon" title="Edge Mobile" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Edge Mobile</abbr> <abbr class="only-icon" title="Firefox for Android" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Firefox for Android</abbr> <abbr class="only-icon" title="Opera for Android" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Opera for Android</abbr> <abbr class="only-icon" title="iOS Safari" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">iOS Safari</abbr> <abbr class="only-icon" title="Samsung Internet" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Samsung Internet</abbr> <abbr class="only-icon" title="Node.js" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Node.js</abbr>
--- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
Basic support <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>45 <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>Yes <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>22

<abbr class="only-icon" title="See implementation notes" style="font-style: normal !important; padding: 0px; border: 0px; cursor: help; text-decoration: none; margin: 0px 2px;">Notes</abbr>

打开 | <abbr class="bc-level-no only-icon" title="No support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">No support</abbr>No | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>32 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>10 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>45 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>45 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>Yes | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>22

<abbr class="only-icon" title="See implementation notes" style="font-style: normal !important; padding: 0px; border: 0px; cursor: help; text-decoration: none; margin: 0px 2px;">Notes</abbr>

打开 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>32 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>10 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>5.0 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>Yes |
| Trailing comma in parameters | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>58 | <abbr title="Compatibility unknown; please update this." style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">?</abbr> | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>52 | <abbr class="bc-level-no only-icon" title="No support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">No support</abbr>No | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>45 | <abbr title="Compatibility unknown; please update this." style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">?</abbr> | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>58 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>58 | <abbr title="Compatibility unknown; please update this." style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">?</abbr> | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>52 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>45 | <abbr title="Compatibility unknown; please update this." style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">?</abbr> | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>7.0 | <abbr class="bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: none;">Full support</abbr>Yes |

Legend

<dl style="font-style: normal !important; margin: 0px 0px 20px; padding: 0px; border: 0px; box-sizing: border-box; max-width: 42rem; display: grid; grid-template-columns: 30px 1fr 30px 1fr;">

<dt style="padding: 0px; border: 0px; font-style: normal; font-weight: 700; display: block; margin: 0px 0px 5px;"><abbr class="bc-level bc-level-yes only-icon" title="Full support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: underline dotted;">Full support </abbr></dt>

<dd style="font-style: normal !important; padding: 0px 0px 0px 20px; border: 0px; display: block; margin: 0px 10px 5px;">Full support</dd>

<dt style="padding: 0px; border: 0px; font-style: normal; font-weight: 700; display: block; margin: 0px 0px 5px;"><abbr class="bc-level bc-level-no only-icon" title="No support" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: underline dotted;">No support </abbr></dt>

<dd style="font-style: normal !important; padding: 0px 0px 0px 20px; border: 0px; display: block; margin: 0px 10px 5px;">No support</dd>

<dt style="padding: 0px; border: 0px; font-style: normal; font-weight: 700; display: block; margin: 0px 0px 5px;"><abbr class="bc-level bc-level-unknown only-icon" title="Compatibility unknown" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: underline dotted;">Compatibility unknown </abbr></dt>

<dd style="font-style: normal !important; padding: 0px 0px 0px 20px; border: 0px; display: block; margin: 0px 10px 5px;">Compatibility unknown</dd>

<dt style="padding: 0px; border: 0px; font-style: normal; font-weight: 700; display: block; margin: 0px 0px 5px;"><abbr class="only-icon" title="See implementation notes." style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px; cursor: help; text-decoration: underline dotted;">See implementation notes.</abbr></dt>

<dd style="font-style: normal !important; padding: 0px 0px 0px 20px; border: 0px; display: block; margin: 0px 10px 5px;">See implementation notes.</dd>

</dl>

相关链接

</article>

文档标签和贡献者

标签:

此页面的贡献者: wangbangkun, ColinJinag, zjjgsc, Harleywww, huangll, LeoQuote, jjc, ywjco, Warden, xgqfrms-GitHub, zhangchen, anjia, StevenYuysy,ZZES_REN, tjyas, Gary-c, linzhihuan, guonanci, shifengchen, unliar, MichelleGuan, slimeball, LangDonHJJ, zhangzju, Aisi, muzhen, Meteormatt, Ende93, Ovilia,solome, zilong-thu, jy1989, teoli, ziyunfei

最后编辑者: wangbangkun, <time datetime="2018-07-30T01:34:50.215940-07:00" style="font-style: normal !important; margin: 0px; padding: 0px; border: 0px;">Jul 30, 2018, 1:34:50 AM</time>

<nav class="crumbs" role="navigation" style="font-style: normal !important; display: block; border-style: solid; border-color: rgb(215, 215, 215); border-image: initial; border-width: 0px 0px 1px; margin: 0px 0px 20px; padding: 0px 0px 15px; font-size: 0.88889rem;">

  1. Web 技术文档
  2. Java<wbr style="font-style: normal !important;">Script
  3. Java<wbr style="font-style: normal !important;">Script 参考文档
  4. 函数
  5. 箭头函数

</nav>

箭头函数传参之用变量解构的方式来传参

let set = ({num1,num2}) => {
            return num1 + num2;
        } 
        console.log(set({num1:3,num2:4}))

普通方式传参

 let set = (num1,num2) => {
            return num1 + num2;
        } 
        console.log(set(3,4))
    `//箭头函数简单版`
    // 1、当函数参数只有一个的时候,()可以省略,但是没有参数的时候,括号不可以省略
    //2、当函数体{}中只有一行return语句的时候,中括号以及return语句可以省略。
    //以下是个例子
        let add = a => a;  
        console.log(add(3));
上一篇下一篇

猜你喜欢

热点阅读