手写 bind

手写 bind

  •  思路:
  1.   myBind是挂载在Function的原型上的
  2.  返回值是一个函数,该函数的返回值是原函数的返回结果
  3.  原函数的参数不变
function fn(age, sex) {
    this.age = age
    this.sex = sex
    console.log(this);
}
// myBind是挂载在Function的原型上的
Function.prototype.myBind = function () {
    // 保存调用 myBind 的上下文 this
    const _this = this
    // 保存调用 myBind 时的参数
    const args = Array.prototype.slice.call(arguments)
    // 保存调用 myBind 时传的 this
    const newThis = args.shift()
    // 返回值是一个函数
    return function () {
        // 返回值是原函数的返回结果
        // 原来的函数要执行,并且将 this 改变为调用 myBind 时传的参数1,并将调用 myBind 时传递的参数传递给 原函数
        _this.apply(newThis, args)
    }
}

const obj = {
    name: 'zs'
}

const fnMyBind = fn.myBind(obj, 18, '男')
fnMyBind()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值