(JavaScript)手写bind

bind方法实现思路:

1、bind方法不会立即执行,会返回一个函数(闭包)
2、实现作用域绑定(apply)
3、参数传递(apply的数组传参)
4、当绑定函数作为构造函数时,绑定的this会失效并进行原型继承

Function.prototype.mybind = function(context) {
    if(typeof this !== 'function'){
        throw new Error('Mybind should be called by function !');
        return;
    }
    const self = this;
    const args = [ ...arguments ].slice(1);
    let inner = function() {
        let _this = this instanceof inner ? this : context;
        return self.apply(_this, [ ...args, ...arguments ]);
    }

    let Fn = function() {};
    Fn.prototype = this.prototype;
    inner.prototype = new Fn();

    // inner.prototype = this.prototype;
    // 如果写inner.prototype = this.prototype 
    // 那么当改变inner的原型时,目标函数的原型也会被改变
    return inner;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值