Skip to content

箭头函数

写法如名字一样用箭头连接参数部分与处理部分;当参数为一个时,括号是可选的;当处理为一句 js 代码时,括号是可选的。从写法上看箭头函数比普通函数更为简洁。

js
// 标准写法
const fn = (a, b) => {
  return a * b
}

// 省略写法
const fn = a => a * 2

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

  • 箭头函数没有自身 this,它 this 取自定义时上下文,并且不可该改;而普通函数 this 取自调用时;
js
const fn = () => console.log(this)
const fm = function () {
  console.log(this)
}
const obj = { name: '张三' }

fn.call(obj) // window
fm.call(obj) // { name: '张三' }
  • 箭头函数没有原型,不能作为构造函数执行,既不能使用 new
js
const fn = name => {
  this.name = name
}
const fm = function (name) {
  this.name = name
}
console.log(fn.prototype) // undefined
console.log(fm.prototype) // { constructor: ƒ }
new fn() // fn is not a constructor
new fm()
  • 箭头函数没有函数参数对象 arguments
js
const fn = name => {
  console.log(arguments) // arguments is not defined
}
const fm = function (name) {
  console.log(arguments)
}
fn()
fm()

应用场景

  • 利用箭头函数 this 指向特性,来访问当前上下文;普通函数需更改函数 this。
js
const obj = {
  age: '18',
  getAge() {
    console.log(this) // obj

    setTimeout(function () {
      console.log(this) // window
    })

    setTimeout(
      function () {
        console.log(this) // obj
      }.bind(obj)
    )

    setTimeout(() => {
      console.log(this) // obj
    })
  }
}
obj.getAge()