js手写call|、apply、bind

核心思路:

       1、函数方法调用 需要挂载到Funtion构造函数的prototype上        

     

手写call

Function.prototype.myCall = function(ctx,...args){
    // 判断ctx有没有传进来值 如果没有就赋值window
    ctx = ctx || window
    // 在传进来的对象上面新增一个属性 保存this
    ctx._this = this
    // 调用该函数、传参、保存
    const resulte =  ctx._this(args)
    // 删除_this属性
    delete ctx._this
    //  返回 调用函数的结果
    return resulte
}

手写apply

Function.prototype.MyApply = function (obj, arg) {
  let fn = this //this表示函数
  // 如果要是obj为undefined或者null时,设置其为window,
  // 如果是基本数据类型,则将其设置为对象类型
  let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
  thisArg.fn = fn
  arg = arg || [] //如果arg不存在,则直接赋值为[]
  let res = thisArg.fn(...arg)
  delete thisArg.fn
  return res
}

手写bind

Function.prototype.MyBind = function(obj, ...args1) {
    let fn = this
    let thisArg = (obj === undefined || obj === null) ? window : Object(obj)
    
    return function(...args2) {
      thisArg.fn = fn
      let args = [...args1, ...args2]
      let result = thisArg.fn(...args)
      delete thisArg.fn
      return result
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值