js 手写call、apply、bind

function fn(a, b) {
   console.log('a', a);        // 10
   console.log('b', b);        // 20
   console.log('this', this)   // {x: 1}
   return 'hello'
}

const res = fn.myCall({x: 1}, 10, 20)
console.log(res)  // hello

const res1 = fn.myApply({x: 1}, [10, 20])

Function.prototype.myCall = function () {
   const [t, ...others] = Array.prototype.slice.call(arguments);
   const self = this; // fn 调用的 myCall, 这里的 this 是 fn
   // fn(others) 但是 this指向有问题
   t.fn = self;
   const res = t.fn(others) // 接收 fn 的返回值
   delete t.fn;
   return res;
}

Function.prototype.myApply = function () {
   const [t, others] = Array.prototype.slice.call(arguments);
   const self = this; // fn调用的 myApply, this 指向 fn
   // fn(...others) 这样调用 this 指向 window
   // 现在想让 this 指向 t
   t.fn = self;
   const res = t.fn(...others);
   delete t.fn;
   return res;
}

Function.prototype.myBind = function () {
    const self = this; // 谁调用的myBind, this就指向谁, fn
    const [t, others] = Array.prototype.slice.call(arguments);
    return function () {
        return self.call(t, ...others);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值