ES6之箭头函数(Arrow Function)

来源:互联网 发布:虚拟机装mac os 编辑:程序博客网 时间:2024/04/29 20:32

箭头函数(Arrow Function)

  目录:

  • 箭头函数Arrow Function
    • 语法
      • 单一参数的单行箭头函数
      • 多参数的单行箭头函数
      • 多行箭头函数
      • 无参数箭头函数
    • this 穿透
    • 程序逻辑注意事项
    • 编写语法注意事项


语法

单一参数的单行箭头函数

  用法:arg => statement

const fn = foo => `${foo} hello`; // means retuen `foo + 'hello'`

  常用于简单的处理函数,比如过滤:

let array = ['a', 'bc', 'def', 'ghij'];array = array.filter(item => item.length >= 2);  // bc, def, ghij

多参数的单行箭头函数

  用法:(arg1, arg2) => statement

const fn = (foo, bar) => foo + bar

  常用于数组的处理,如排序:

let array = ['a', 'bc', 'def', 'ghij'];array = array.sort((a, b) => a.length < b.length);  // ghij, def, bc, a 

多行箭头函数

  用法:args.. => {statement}

foo => {    return 'hello world';}(foo, bar) => {    return foo + bar;}

无参数箭头函数

  用法:() => statement

const greet = () => 'hello world';

this 穿透

  箭头函数用于将函数内部的 this 延伸至上一层作用域中,即上一层的上下文会穿透到内层的箭头函数中。

const obj = {    hello: 'world',    foo() {        // this        const bar = () => this.hello;        return bar;    }}window.hello = 'ES';window.bar = obj.foo();window.bar();   // 'world'

程序逻辑注意事项

  箭头函数对上下文的绑定是强制性的,无法通过apply或call方法改变。

const a = {    init(){        this.bar = () => this.dam       },    dam: 'hei',    foo(){        return this.dam;    }}const b = {    dam: 'ha'}a.init();console.log(a.foo());  // heiconsole.log(a.foo.bind(b).call(a));  //haconsole.log(a.bar.call(b));  //hei



  不能随意在顶层作用域使用箭头函数。

// 假设当前运行环境为浏览器,则顶层上下文为“window”const obj = {    msg: 'pong',    ping: () => this.msg // Warning!}obj.ping(); // undfinedvar msg = 'bang!';obj.ping(); // bang!

  上面代码的等价代码:

var that = this;var obj = {    //...    ping: function(){        retuen that.msg;    // Warning    }}// 又等价为var that = this;var obj = { /* ... */  };obj.ping = function(){    return that.msg;}



  同样地,在箭头函数中也没有arguments、 callee 甚至 caller 等对象。

const fn = () =>{    console.log(arguments);}fn(1, 2);  // ReferenceError: arguments is not defined           //事实上输出了{ i: 0, l: false, exports: {} }

  若有使用 arguments 的需求,可以使用后续参数来获取参数列表。

const fn = (...args) =>{    console.log(args[0]);}fn(1, 2);   // 1

编写语法注意事项

  在使用单行箭头函数时,请不要对单行的函数体做任何换行
  参数列表的右括弧、箭头需要保持在同一行内。
  单行箭头函数只能包含一条语句,但如果是错误抛出语句(throw)等非表达式的语句,则需要使用花括号包裹

const fn = x => {throw new Error('some error message')};

  若要使用单行箭头函数直接返回一个对象字面量,请使用一个括号包裹该对象字面量,而不是直接使用大括号,否则 ECMAScript 解析引擎会将其解析为一个多行箭头函数。

const ids = [1, 2, 3];const users = ids.map(id => {id: id});// 错误: [undefined, undefined, undefined]const users = ids.map(id => ({id: id}));// 正确: [{id: 1}, {id: 2}, {id: 3}]