箭头函数

75 阅读1分钟

箭头函数的缺点

  • 没有arguments
  • 无法通过apply``call``bind改变this
    • 箭头函数的this是在定义时继承而来,无法在运行时进行改变

箭头函数不适用的情况

  • 对象方法内使用this

在定义object的时候,{}并不会生成一个作用域,此时{}内的this是指向window的,而箭头函数继承这一this,就会导致错误。

const obj = {
    name:'kang',
    getName:()=>{
       
       return this.name
    }
}

console.log(obj.getName()) //undefined
  • 原型方法

原理同上

const obj = {
    name:'kang'
}
obj.__proto__.getName = ()=>{
       
    return this.name
}

console.log(obj.getName()) //undefined
  • 构造函数

依然是this指向导致的问题

const Foo = (name, age) => {
    this.name = name
    this.age = age
}
const f = new Foo('kang', 20)
//Uncaught TypeError: Foo is not a constructor
  • 动态上下文中的回调函数
const btn = document.getElementById('btn')
btn.addEventListener('click', () => {
    console.log(this === window); // true
    this.innerHTML = 'clicked'
})
  • Vue生命周期和method中

Vue生命周期,method中若使用箭头函数,效果和object内方法使用箭头函数效果是一样的,this指向问题

{
    data(){
        return {
            name:'kang'
        }
    },
    methods: {
        getName:()=>{
            return this.name // 报错
        }
    },
    mounted:()=>{
        console.log(this.name); // 报错
    }
}

class内是可以使用箭头函数的,不会有this指向问题