apply,call,bind 改变this的指向

apply call bind

call() 方法分别接受参数
apply() 方法接受数组形式的参数。
bind() 方法,分别接受参数,并返回一个函数,不会调用这个函数
  1. apply 方法,可以改变调用函数的调用者,person1 可以调用person 的fullName()

    var person = {
        fullName: function() {
            return this.firstName + " " + this.lastName;
        }
    }
    var person1 = {
        firstName: "Bill",
        lastName: "Gates",
    }
    person.fullName.apply(person1);  // 将返回 "Bill Gates"
    
  2. apply 方法中接受参数

    var person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"John",
      lastName: "Doe"
    }
    person.fullName.apply(person1, ["Oslo", "Norway"]);
    
  3. apply与call()方法对比,是参数的格式不同

    var person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + "," + city + "," + country;
      }
    }
    var person1 = {
      firstName:"John",
      lastName: "Doe"
    }
    person.fullName.call(person1, "Oslo", "Norway");
    
  4. bind 方法的使用

    this.x = 9;  // 在浏览器中,this 指向全局的 "window" 对象
    var module = {
    x: 81,
    getX: function () {
      return this.x;
      }
    };
    let retrieveX = module.getX;
    let  boundGetX = retrieveX.bind(module); 
    
    // 创建一个新函数,把 'this' 绑定到 module 对象
    // 新手可能会将全局变量 x 与 module 的属性 x 混淆
    let a = module.getX(); // 81 module 调用getx,所有this 是module
    let b = retrieveX(); // 9 因为函数是在全局作用域中调用的,相对于windows.getX
    let c = boundGetX(); // 81
    
    
改变 this的指向
  1. 在默认情况下,使用 window.setTimeout() 时,this 关键字会指向 window (或 global)对象。当类的方法中需要 this 指向类的实例时,你可能需要显式地把 this 绑定到回调函数,就不会丢失该实例的引用。

  2. 使用箭头函数,在箭头函数里面的this,不管是谁调用这个函数,this在声明的时候已经确定下来了

  3. 在函数的内部,声明一个变量来存储 this

  4. 也可以使用apply、call、bind改变this 的指向

    var a = {
    name: "Cherry",
    func1: function () {
      console.log(this.name)
    },
    
    // 使用箭头函数 改变this的指向
    func2: function () {
      setTimeout(() => {
        this.func1()
      }, 100);
    },
    
    // 声明一个变量_this 保存this, 既_this 指向对象a
    func3: function () {
      let _this = this
      setTimeout(function(){
        _this.func1()
      }, 100);
    },
    
    // 使用apply 改变this的指向
    func4: function () {
      setTimeout(function () {
        this.func1()
      }.apply(a), 100);
    },
    // 使用call 改变this的指向
    func5: function () {
      setTimeout(function () {
        this.func1()
      }.call(a), 100);
    },
    
    // 使用bind 改变this的指向
    func6: function () {
      setTimeout(function () {
        this.func1()
      }.bind(a)(), 100);
    },
    
    // 不改变this 的指向,setTimeout运行时,this 指向windows
    func5: function () {
      setTimeout(function () {
        this.func1()
      }, 100);
    }
    };
    
    a.func2() // Cherry
    a.func3() // Cherry
    a.func4() // Cherry
    a.func4() // Cherry
    a.func5() // this.func1 is not a function
    
传入参数的形式
  1. call apply bind 的参数形式大体相同,第一个参数是调用setName 的对象,在下面的例子里就是arg,apply 方法接受的参数是一个数据list,bind 和 call, 分别传入其他参数,注意的是call 和apply 会调用函数,bind 会返回一个新的函数,所以bind方法要在最后加一对括号()

    let obj = {
        
        firstName: 'xiaoYi',
        lastName: 'xiaoYi',
    
        setName: function (firstName, lastName) {
          this.firstName = firstName
          this.lastName = lastName
         },
    
        setName1: (firstName,lastName) => {
          this.firstName = firstName
          this.lastName = lastName
         }
    }
    
    let setName = obj.setName
    let setName1 = obj.setName1
    
    setName("小", "毅") // firstName:'小' lastName:'毅' obj.firstName:'xiaoYi' obj.lastName:'xiaoYi'
    setName1('小', '毅') // obj.firstName:'小'obj.lastName:'毅'
    setName.call(obj, "小", "毅") // obj.firstName:'小'obj.lastName:'毅'
    setName.apply(obj, ['小', '毅']) // obj.firstName:'小'obj.lastName:'毅'
    setName.bind(obj, '小', '毅')() // obj.firstName:'小'obj.lastName:'毅'
    
其他使用方式
  1. 因为数组上没有Max 方法,可以通过改变 apply 调用Math上的max 方法

    // 第一个参数为什么可以随便写apply的第一个参数是函数中的this值,如果add函数里面没有用到this,那么这个this参数就可以随便传入一个值,但是为了简便一般就传入null,当然你传入1,undefined,'hello'都可以,只不过都习惯传入null,代表函数里面并没有用到this的值
    let list = [2,3,4,5,7]
    let max = Math.max.apply(null,list) // 第一个参数 null
    let max = Math.max.apply(1,list) // 第一个参数 number
    let max = Math.max.apply('str',list) // 第一个参数 string
    let max = Math.max.apply({},list)// 第一个参数 object
    let max = Math.max.apply([],list)// 第一个参数 list
    let max = Math.max.apply(function(){},list)// 第一个参数 function
    console.log(max); // 7
    
  2. slice 方法可以用来将一个类数组(Array-like)对象/集合转换成一个新数组。你只需将该方法绑定到这个对象上。 一个函数中的 arguments 就是一个类数组对象的例子。

    // 将Array 原型上的slice方法返回
    function list() {
      return Array.prototype.slice.call(arguments);
    }
    
    // 简化
    function list() {
      return [].slice.call(arguments)
    }
    var list1 = list(1, 2, 3); // [1, 2, 3]
    
参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

https://juejin.cn/post/6844903496253177863#heading-2

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值