箭头函数

134 阅读1分钟

knockkey总结 1.0 箭头函数没有this, 它的this是通过作用域链查到外层作用域的this, 且指向函数定义时的this而非执行时

1.1 不能用call/apply/bind修改this指向, 但可以通过修改外层作用域的this来间接修改

  1. 不可以用作构造函数, 不能使用new命令, 否则会报错
  2. 箭头函数没有arguments对象, 如果要用, 使用rest参数代替
  3. 不可以使用yield命令, 因此箭头函数不能用作Generator函数
  4. 箭头函数没有 prototype 属性
  5. 不适用于动态上下文中的回调函数
    const btn1 = document.getElementById('btn1')
    const btn2 = document.getElementById('btn2')
    btn1.addEventListener('click', () => {
      console.log(this === window);
      this.innerHTML = 'clicked'
    })
    btn2.addEventListener('click', function () {
      console.log(this === window);
      this.innerHTML = 'clicked'
    })
  1. 不适用于Vue声明周期和method
data(){return {name:'谭'}}
methods:{
    getName:()=>{
		//报错   Cannot read properties of undefined (reading 'name')     
        return this.name
    },
    getName(){
        return this.name  //正常
    }
},
mounted:() => {
    //报错   Cannot read properties of undefined (reading 'name') 
    console.log('msg',this.name)
},
mounted(){
       console.log('msg',this.name)//正常
}