call,apply,bind的实现

// call实现
Function.prototype.callFun = function(obj, ...args) {
  if (!obj) {
    obj = typeof window === 'undefined' ? global : window
  }
  obj.func = this
  let res = obj.func(...args)
  delete obj.func
  return res
}
// apply实现
Function.prototype.applyFun = function(obj, args) {
  if (!obj) {
    obj = typeof window === 'undefined' ? global : window
  }
  obj.func = this
  let res = obj.func(...args)
  delete obj.func
  return res
}

// bind实现
Function.prototype.bindFun = function(obj, ...args) {
  let _this = this
  if (!obj) {
    obj = typeof window === 'undefined' ? global : window
  }
  return function() {
    _this.call(obj, ...args, ...arguments)
  }
}
var name = 'aaa'
var obj = { name: 'bbb' }
function a(age, job) {
  console.log(this.name, '我今年' + age + '岁', '我的工作是' + job)
}

let funs = a.bindFun(obj, 20)
funs('敲代码')

原理:

首先是函数调用,所以在Function类的原型上添加这个方法,首先判断第一个参数存不存在,不存在判断是否在window环境下,

主要是给第一个参数添加一个随机属性值为this,该this指向调用这个方法的fun,此时再调用这个对象,的这个方法,方法就会指向这个绑定对象,拿到返回值后,删掉随机对象,返回调用后结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值