博客
关于我
2024前端面经---改变this指向问题(call、apply、bind)_apply改变this
阅读量:807 次
发布时间:2023-04-17

本文共 1708 字,大约阅读时间需要 5 分钟。

this指向改变方法详解

一、this指向基础知识

this是一个关键字,其指向取决于函数的类型和调用方式。在 JavaScript 中,this的默认指向是 window对象。以下是两种主要函数类型对this的影响:

  • 普通函数:

    this 的指向取决于谁调用了函数。如果没有明确调用者,this 默认指向 window。

  • 箭头函数(ES6):

    • 如果箭头函数嵌套在另一个函数中,this 指向外层函数的上下文。
    • 如果箭头函数没有外层函数包裹,this 默认指向 window。
  • 以下是实际场景中的 this 指向表现:

    • 场景一:

      直接在控制台打印 this,结果是 window。

    • 场景二:

      使用 setTimeout 定时器执行回调函数,回调函数中的 this 仍然指向 window。

    • 场景三:

      事件处理中绑定的 this 指向目标DOM元素。

    • 场景四:

      对象方法中的 this 指向调用者对象。

    • 场景五:

      箭头函数在对象字面量中使用时,this 指向 window,因为无法继承对象的上下文。

    二、改变this指向的三种方法

  • call() 方法

    • 通过 call() 方法可以指定 this 的指向。
    • 传入的第一个参数会被赋值给 this。
    • 例如:
      let obj1 = { name: 'james', getName1: function(a, b, c) { ... } };obj1.getName1.call(obj2, 1, 2, 3);
    • 这时 this 会指向 obj2。
  • apply() 方法

    • 和 call() 类似,但主要用于传递多个参数。
    • 例如:
      let obj1 = { name: 'james', getName1: function(a, b, c) { ... } };obj1.getName1.apply(obj2, [1, 2, 3]);
    • 这时 this 会指向 obj2,并将参数 1, 2, 3 传递给函数。
  • bind() 方法

    • 用于长期绑定 this 的指向,返回一个新的函数。
    • 例如:
      let boundFunc = obj1.getName1.bind(obj2);boundFunc(1, 2, 3);
    • 这时 this 始终指向 obj2。
  • 三、实战演练

    示例一:使用 call() 改变 this 指向

    let obj1 = { name: 'james', getName1: function(a, b, c) { console.log(`getName ${this.name}`); } };let obj2 = { name: 'davis' };obj1.getName1.call(obj2, 1, 2, 3);

    执行后,getName 会输出 davis,并显示参数 1, 2, 3。

    示例二:使用 apply() 改变 this 指向

    let obj1 = { name: 'james', getName1: function(a, b, c) { console.log(`getName ${this.name}`); } };let obj2 = { name: 'davis' };obj1.getName1.apply(obj2, [1, 2, 3]);

    执行后,结果与 call() 相同。

    示例三:使用 bind() 绑定 this

    let obj1 = { name: 'james', getName1: function(a, b, c) { console.log(`getName ${this.name}`); } };let obj2 = { name: 'davis' };let boundFunc = obj1.getName1.bind(obj2);boundFunc(1, 2, 3);

    执行后,getName 会始终输出 davis。

    四、总结

    通过 call()、apply() 和 bind() 三种方法,可以精确控制 this 的指向。掌握这些方法是 JavaScript 开发的核心技能之一。

    转载地址:http://yxgfk.baihongyu.com/

    你可能感兴趣的文章
    python中函数接受参数为*args, **kwargs怎么办
    查看>>
    Python中切片的高效迭代
    查看>>
    python中列表乘法、eval、lambda、hasattr、assert、*(星)等的用法
    查看>>
    Python中制作词云的WordCloud参数详解
    查看>>
    Python中可用和使用的系统内存?
    查看>>
    python中存根文件(.pyi)的用途是什么?
    查看>>
    Python中实现ASCII码与字符相互转换
    查看>>
    Python中实现获取所有微信好友的头像并拼接成一张图片
    查看>>
    Python中对象的布尔值
    查看>>
    python中对集合的操作
    查看>>
    python中将列表转换为元组的时间复杂度,反之亦然
    查看>>
    Python中布尔表达式的求值
    查看>>
    python中很常用的10个内置函数整理(初学必备)
    查看>>
    python中打印二维列表数据
    查看>>
    python中打散数组shuffle
    查看>>
    Python中执行外部命令
    查看>>
    Python中拼接numpy数组-ChatGPT4o作答
    查看>>
    Python中提示:no module named 'PIL'
    查看>>
    Python中提示:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position
    查看>>
    python中数据类型存储_浅谈Python中的数据类型
    查看>>