全网最详细手写bind

手写bind

  • 在写代码前,一定要分析这个api或者关键字实现了什么,拥有什么功能,如果对其原理认识不到时,也不能达到一比一还原

bind

  1. bind执行返回的是一个新的函数
  2. 这个函数可以被new关键字执行,执行后this指向window(原本的执行是)
  3. 返回的函数拥有其构造函数原型上的方法
    下面我们看代码:
        Function.prototype.mybind = function () {
    
    
            if (typeof this !== 'function') {
    
    
                throw new Error('The Caller is not a Function')
            }
            const argsArr = [...arguments]
            const args = argsArr.shift();
            const self = this;
            const fToBind = function () {
    
    
                console.log('返回函数的参数', arguments);
                const isNew = this instanceof fToBind; // this是否是fToBind的实例 也就是返回的fToBind是否通过new调用
                const context = isNew ? this : Object(args); // new调用就绑定到this上,否则就绑定到传入的objThis上
                return self.apply(context, argsArr.concat([...arguments]));
            }
            if (self.prototype) {
    
    
                fToBind.prototype = Object.create(self.prototype)
            }
            return fToBind
        }

- 这样就实现了手写一个bind,其实很简单,在手写代码时我们首先要想清楚这个关键字或者api实现了什么,我们分布还原就好了

猜你喜欢

转载自blog.csdn.net/qq_52648305/article/details/126255827