跳到主要内容

ES6箭头函数this指向

箭头函数非常方便,但是在使用箭头函数时要注意箭头函数和匿名函数 this 的指向会不同。

匿名函数 this 指向

指向最终调用函数的对象, 如果没有被上一级调用, 指向 window(undefined)

let obj={
birth:1980,
getAge:function(){
// this 指向obj
let b = this.birth
let fun=function(){
//this 指向window(undefined)
return new Date().getFullYear()=this.birth
}
return fun()
}
}
console.log(obj.getAge()) // NaN

箭头函数 this 指向

箭头函数中的 this 由上下文确定, 即箭头函数中的 this 等于上下文(conext)的 this

var obj = {
birth: 1990,
getAge: function () {
// this 指向obj
var b = this.birth

// this指向obj
// fn 的上下文在getAge 中, getAge的this 为obj
var fn = () => new Date().getFullYear() - this.birth
return fn()
},
}
console.log(obj.getAge()) // 26

箭头函数 this 不可变

箭头函数中的 this 指向是不可变的,call(), apply(), bind() 这些方法也不能改变 this 的指向。

window.name = 'window'
var obj = {
name: 'obj',
}
function showName() {
// this 指向window
console.log(this.name)
}
//传入call() obj, 改变了showName 中的this
showName.call(obj) // obj

箭头函数

window.name = 'window'
var obj = {
name: 'obj',
}
const showName = () => {
// this 指向window
console.log(this.name)
}
// 传入call() obj, 不会改变showName 中的this
showName.call(obj) // window

其他

  1. 箭头函数不能使用new 来实例化对象
  2. 箭头函数没有arguments 对象, 但是可以使用 rest 参数
const fn = (...args) => args
fn(1, 2, 3) // [1,2,3]

参考 简单说 JavaScript 的箭头函数