• JS中箭头函数和普通函数的区别


    JS中箭头函数和普通函数的区别

    原文链接

    打印的结果不同

    var person = {
      say: function () {},
      say2: () => {}
    }
    console.dir(person.say)
    console.dir(person.say2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    在这里插入图片描述

    • 箭头函数是没有prototypearguments属性的

    this的指向不同

    • 普通函数的this 是在函数运行时候确定的, 基本满足谁调用指向谁, 特殊情况除外
    • 箭头函数的this 是在函数定义就确定了, 因为箭头函数是没有this, 所以内层的this就指向箭头函数上层的作用域, 并且不可以通过call, apply, bind改变this指向
    var aaaa = '大火车'
    var person = {
      aaaa: '小火车',
      say: function () {
        console.log(this.aaaa)
      },
      say2: () => {
        console.log(this.aaaa)
      }
    }
    person.say() // 小火车
    person.say2() // 大火车
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    普通函数say中的this因为是被person对象调用, 所以this就指向了person对象, 打印的结果就是小火车

    箭头函数say2中的this是在函数定义的时候就确定了, 而且对象不构成独立的作用域, 所以this就指向了顶级作用域window, 打印结果就是大火车

    箭头函数不能作为构造函数

    function Person() {
    }
    const per = new Person()
    
    • 1
    • 2
    • 3

    使用new 创建构造函数的四个步骤

    1. 创建一个空对象
    2. 链接到原型
    3. 改变this指向
    4. 返回新的对象
    // 1.创建一个空对象
    let obj = {}
    // 2.将对象的对象原型赋予Person的原型对象
    obj.__proto__ = Person.prototype
    // 3.改变this指向
    let result = Person.call(obj, ...arguments)
    // 4. 返回新的对象
    return result
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    因为箭头函数是没有prototype原型对象的, 因此如果直接使用new 就会报错

    箭头函数没有自己的arguments

    const aa = ()=> {
      console.log(arguments)
    }
    aa()
    
    • 1
    • 2
    • 3
    • 4

    在这里插入图片描述
    因为这里的箭头函数往上层作用域查找arguments, 但是全局的作用域window是没有arguments属性的, 所以报错


    function aa() {
      const bb = ()=> {
        console.log(arguments)
      }
      bb()
    }
    aa() // Arguments [callee: ƒ, Symbol(Symbol.iterator): ƒ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述
    这里的箭头函数会找到上层作用域aa函数的arguments

  • 相关阅读:
    【Dubbo3高级特性】「系统级别检查」服务端和消费端启动时检查
    Apache Log4j2漏洞
    Vue3中自定义事件实现子组件向父组件传递数据
    从零开始的C++(三)
    【重识云原生】第四章容器基础6.4.10.5节——Statefulset原理剖析
    【Python脚本进阶】1.2、python脚本基础知识(下)
    【数据结构】二叉树的遍历
    kotlin 函数
    百利天恒更新招股书:上半年收入约3亿元,持续加大研发投入
    论如何让您的网站更好看?
  • 原文地址:https://blog.csdn.net/weixin_43972992/article/details/125506993