为什么箭头函数不能当构造函数

230 阅读1分钟

箭头函数的概念

  • 箭头函数没有自己的this,箭头函数的this不是调用的时候决定的,而是在定义的时候出在的对象就是它的this
  • 扩展理解:箭头函数的this看外层的是否有函数,如果有,外层函数的this就是内部箭头函数的this,如果没有,则this是window
  • 不绑定arguments
  • 箭头函数不能用作构造器,和new一起回抛出错误
  • 箭头函数没有prototype属性

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

        function Person(name){
            this.name=name
        }
        const person=name=>{
            this.name=name
        }
        console.dir(Person)
        console.dir(person)

52f13e64467448216688134247b7c33.png

  • 缺少arguments
  • 缺少caller --无法确定上下文
  • 缺少prototype
function myNew(fn,...args){
    const obj={}
    //缺少fn.prototype
    obj.__proto__=fn.prototype
    //没有自己的this call()函数无法改变箭头函数的指向
    const res=fn.apply(obj,args)
    return typeof res ==='object' ? res :obj
}

缺少了这3个属性,实例化的过程就会处处收到影响,所以不能使用箭头函数当做构造函数的结论也就不言自明。

面试攻略

  • 首先分期箭头函数和构造函数的区别
    • 缺少arguments
    • 缺少caller 无法确定上下文
    • 缺少prototype
  • 通过实例化过程逐步分析