【小白鲨笔记】js面试题(十七)

十七、箭头函数vs普通函数

  1. this指向问题

    • 箭头函数:this指向在定义时就决定的 ➡️ 不可修改(call、apply、bind)

      • this指向:外层第一个普通函数的this(没有自己的this)
    • 普通函数:使用时决定this指向 ➡️ 可通过call、apply、bind修改

      • this指向:调用该函数的对象
    let obj = {
        a: function(){ console.log(this) }, //this = obj
        b: () => { console.log(this) } //this = window
    }
    
    let obj = {
        run: function(){
            console.log(this) // obj
            return () => { console.log(this) } //obj
        },
        speak: function(){
            return function(){ console.log(this) }
        }
    }
    obj.run().call(window) //未更改为window, this = obj
    obj.run()() // this = obj
    obj.speak() // this = window
    
  2. 构造函数

    • 箭头函数:不能当作构造函数new(也不可用super)

    • 普通函数:可以new = 构造函数

    let run = () => { return 111 }
    console.log(new run()) //报错
    
  3. 原型

    • 箭头函数:没有prototype

    • 普通函数:有prototype

    let run = () => {}
    console.log(run.prototype) //undefined
    
  4. 参数

    • 箭头函数:没有arguments ➡️ 用rest参数解决

      let fn = (...args) => { console.log(args) }
      fn() //数组形式输出
      
    • 普通函数:有arguments

    let run = () => { console.log(arguments) }
    run() //报错:arguments没有定义
    let walk = function(){ console.log(arguments) }
    walk() //Arguments[callee:f, Symbol(Symbol.iterator)]
    
  5. Generator函数:

    • 箭头函数:不能使用yeild关键字 ➡️ 不可以当作Generator函数

    • 普通函数:可使用yield关键字 ➡️可用于Generator函数

    箭头函数:this指向上下文、不可new、没有原型 ➡️ 匿名函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值