改变this指向的三种方式

1. call() 

使用 call 方法调用函数,同时指定被调用函数中 this 的值

语法:

fun.call(thisArg, arg1, arg2, ...) 

thisArg:在 fun 函数运行时指定的 this 值

arg1,arg2:传递的其他参数

返回值就是函数的返回值,因为它就是调用函数

 const obj = {
      uname: 'xiaoming'
    }
    function fn(x, y) {
      console.log(this) // window
      console.log(x + y)
    }
    // 1. 调用函数  
    // 2. 改变 this 指向
    fn.call(obj, 1, 2)//改变fn中this的指向,指向obj,并且传入1。2的值
2. apply()

使用 apply 方法调用函数,同时指定被调用函数中 this 的值

语法:

fun.apply(thisArg, [argsArray])

thisArg:在fun函数运行时指定的 this 值

argsArray:传递的值,必须包含在数组里面

返回值就是函数的返回值,因为它就是调用函数

因此 apply 主要跟数组有关系,比如使用 Math.max() 求数组的最大值

 const obj = {
      age: 18
    }
    function fn(x, y) {
      console.log(this) // {age: 18}
      console.log(x + y)
    }
    // 1. 调用函数
    // 2. 改变this指向 
    //  fn.apply(this指向谁, 数组参数)
    fn.apply(obj, [1, 2])
    // 3. 返回值   本身就是在调用函数,所以返回值就是函数的返回值
​
    // 使用场景: 求数组最大值
    // const max = Math.max(1, 2, 3)
    // console.log(max)
    const arr = [100, 44, 77]
    const max = Math.max.apply(Math, arr)
    const min = Math.min.apply(null, arr)
    console.log(max, min)
    // 使用场景: 求数组最大值
    console.log(Math.max(...arr))

不改变指向,可以写null

3. bind()-重点

bind() 方法不会调用函数。但是能改变函数内部this 指向

语法:

fun.bind(thisArg, arg1, arg2, ...)

thisArg:在 fun 函数运行时指定的 this 值

arg1,arg2:传递的其他参数

返回由指定的 this 值和初始化参数改造的 原函数拷贝 (新函数)----所以会返回新函数。

因此当我们只是想改变 this 指向,并且不想调用这个函数的时候,可以使用 bind,比如改变定时器内部的this指向.

document.querySelector('button').addEventListener('click', function () {
      // 禁用按钮
      this.disabled = true
      window.setTimeout(function () {
        // 在这个普通函数里面,我们要this由原来的window 改为 btn
        this.disabled = false
      }.bind(this), 2000)   // 这里的this 和 btn 一样
   

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值