改变this的指向(call、apply、bind)

call和apply的用法很相近,

假设:

let arr = [1,2,3]

A.call(B, arr[1], arr[2], arr[3])                            A.apply(B, arr)

第一个参数:传的是要将this指向的那个东西,像上面我写的也就是将A的this指向B。

第二个参数:call传的是每个值,apply传的是整个数组。(我可以这样记,apply是a开头,数组的英文Array也是a开头。所以apply传的就是数组)

1.call(),  call(thisScope, arg1, arg2, arg3...)

  var name = 'xx';
  var person = {
    name: 'aa',
    sayName: function(){
      console.log(this.name);
    }
  }
  person.sayName() // aa
  person.sayName.call(window) // 将person.sayName的this指向window,而在window下的name=xx,所以这里返回就是 xx

  person.sayName.apply(window) // 和call同理

2. apply(), apply(thisScope, [arg1, arg2, arg3...]);两个参数

var arr = [1,2,5,2,5,3];
Math.max.apply(null,arr); // 其实null就相当于window。也就是将Math.max方法的this指向window下的arr。 也就是相当于arr调用Math.max方法。
Math.max.call(null, ...arr); // 其实也一样

3.bind()  bind(thisScope, arg1, arg2, arg3...)

  var name = 'xx';
  var person = {
    name: 'aa',
    age: 20,
    sayName: function(){
      var _this = this;
      console.log(this.name); // aa
      setTimeout(function(){
        console.log(_this.name); //aa
        console.log(this.name); //aa
        console.log(this.age); // 20
      }.bind(this), 100);
    }
  }
  person.sayName()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值