Skip to content

ES6 之箭头函数 #53

Open
Open
@myLightLin

Description

@myLightLin

以前,定义一个函数是这样:

function sum(a, b) {
  return a + b
}

ES6 出现了箭头函数,可以十分简洁的写出下面这样相同功能的代码:

const sum = (a, b) => a + b

相同的功能,箭头函数可以更精炼地表达我们想要的效果。

箭头函数跟普通函数的区别

  1. 箭头函数没有 this
    在使用普通函数时,我们经常会遇到嵌套函数下,this 丢失的问题。使用箭头函数,this 是根据词法作用域绑定的,就能正确的指向。
  2. 箭头函数没有 arguments
    虽然没有自己的 argument 参数,但是可以通过 rest 把参数收缩到数组里,比如下面这样:
const foo = (...args) => args
foo(1, 2, 3)  // [1, 2, 3]
  1. 箭头函数没有 super 和 new.target
  2. 箭头函数不能作为构造函数使用,也就是不能被 new 调用
  3. 箭头函数没有 prototype 属性

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions