TS bind call apply区别以及实现

1.作用

bind call apply的作用都是改变this的指向:以bind举例如下


var obj = {
    objName: "my name is tom",
    say: function () {
        console.log(this.objName);
    }
};
var kellyObj = {
    objName:"my name is kelly"
}
obj.say(); // my name is tom,this 指向 obj 对象
obj.say.bind(kellyObj)()//"my name is kelly"  ,this 指向 kellyObj 对象

2.再来看下三者区别

bind返回的是一个方法this永久生效,需要调用该返回方法才能执行原方法

apply和call则是直接调用原方法,且this只生效一次,区别在于call直接传递参数,apply需要把参数放到数组里传递


var obj = {
    objName: "my name is tom",
    say: function (age?,city?) {
        console.log(this.objName,age,city);
    }
};
var kellyObj = {
    objName:"my name is kelly"
}

obj.say.bind(kellyObj)(19,"beijing")//"my name is kelly",  19,  "beijing"   ,this 指向 kellyObj 对象
obj.say.apply(kellyObj,[19,"beijing"])//"my name is kelly",  19,  "beijing"   ,this 指向 kellyObj 对象
obj.say.call(kellyObj,19,"beijing")//"my name is kelly",  19,  "beijing"   ,this 指向 kellyObj 对象

3.实现一个apply,另外两个同理,核心思想就是“this”指向谁,就在谁的结构里加一个方法,调用完毕后再删掉这个方法

Function.prototype.myApply = function (context: any, args: any[] = []) {
  if (!context) context = globalThis
  if (typeof context !== 'object') context = new Object(context) // 值类型转化为对象
  const fnKey = Symbol()
  context[fnKey] = this // this 就是当前的函数
  const res = context[fnKey](...args) // 绑定了this 这是立即执行
  delete context[fnKey]
  return res
}

let obj = {
    name:"tom",
    say:function(param,param2){
        console.log(param,param2,this.name)
    }
}
let kellyObj = {
    name:"kelly"
}
obj.say.myApply(kellyObj,["abc","def"])//"abc",  "def",  "kelly" 

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值