JS基础面试题:箭头函数

32 阅读1分钟

箭头函数有什么缺点?

  1. 没有arguments
  2. this是父级作用域的this
  3. 无法通过apply call bind 改变this
  4. 某些箭头函数代码难以阅读

什么时候不能使用箭头函数?

  • 对象方法
  • 对象原型
  • 构造函数
  • 动态上下文的回调函数
  • Vue 的生命周期和method

不适用1 - 对象方法

const obj = {
    name:'jackson',
    getName: ()=>{
        return this.name
    }
}
console.log(obj.getName()) //空的

不适用2 - 原型方法

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

不适用3 - 构造函数

const fn4 = (name,city)=>{
    this.name = name
    this.city = city
}
const f = new Foo('jackson','NewYork') // 无法创建

不适用4 - 动态上下文中的回调函数

const btn1 = document.getElementById('btn1')
btn1.addEventListener('click', ()=> {
    // console.log(this === window)
    this.innerHTML = 'clicked'
})

不适用5 - vue 生命周期和method

{
    data(){return {name:'vue'}},
    methods:{
        getName:()=>{
            return this.name // 报错
        }
    },
    methods:()=>{
        console.log('msg',this.name) // 报错
    },
    mounted(){
        console.log('msg',this.name) // 正常
    }
}

vue 组件本质是一个 js 对象 但是:react 组件(非hooks)本质本质上是一个ES6 class

class Foo{
    constructor(name,city){
        this.name = name
        this.city = city
    }
    getName = () =>{
        return this.name
    }
}
const f = new Foo('react','NewYork')
console.log(f.getName()) // 正常

划重点

  • 要熟练应用箭头函数,也要对函数this arguments 敏感
  • 传统vue组件是js对象, 传统react组件是class,两者不同