美文网首页
call,apply.bind的实现原理

call,apply.bind的实现原理

作者: 那就算了吧_ | 来源:发表于2019-07-24 18:17 被阅读0次
    call, apply, bind都是定义在函数Function原型上的方法,都是改变函数执行的上下文,说的直白点就是改变了函数this的指向。不同的是:call和apply改变了函数的this,并且执行了该函数,而bind是改变了函数的this,并返回一个函数,但不执行该函数。
    • 看下面的例子
    let eat=function(a,b){
      console.log(this)
      console.log(this.name)
      console.log([a,b])
    }
    
    let cat = {
      name:"我是cat",
      eat:eat
    }
    cat.eat(1,2);//cat对象,"我是cat","[1,2]"
    eat.call(cat,1,2);//cat对象,"我是cat","[1,2]"
    

    这里可以人为call的实现其实和为对象添加了一个外部函数然后执行效果差不多,只不过call最后没有为对象添加额外的属性,可以认为是call执行完之后删除掉了新增的属性

    cat.eat(1,2);//cat对象,"我是cat","[1,2]"
    //执行完之后
    delete cat.eat;//之后就等同于call实现的方式
    
    • 下面来看call的内部实现:
    Function.prototype.call = function(thisArg){
       // this指向调用call的对象
        if (typeof this !== 'function') { // 调用call的若不是函数则报错
            throw new TypeError('Error')
        }
      //若thisArg不是函数,或者不存在,thisArg指向window
      thisArg = thisArg || window
      thisArg.fn = this   // 将调用call函数的函数对象添加到thisArg的属性中
      //其实就是上面例子中的这一步
      //cat.eat = eat;
      //去除参数的第一个值后执行这个添加的函数
      const res = thisArg.fn(...arguments.slice(1))
      delete thisArg.fn   // 删除该属性
      return res;
    }
    
    • apply的实现原理和call一样,只不过是传入的参数不同处理不同而已
      //Function.prototype.apply = function(thisArg,args)
      //去除参数的第一个值后执行这个添加的函数
      const res = thisArg.fn(...args);//只是参数处理不用,args这里直接接受数组,直接结构数组即可
    
    • bind的实现原理比call和apply要复杂一些,bind中需要考虑一些复杂的边界条件。bind后的函数会返回一个函数,而这个函数也可能被用来实例化:
    Function.prototype.bind = function(oThis){
            if(typeof this !== 'function'){
                throw new TypeError('被绑定的对象需要是函数')
            }
            var self = this
            var args = arguments.slice(1);
            fBound = function(){ //this instanceof fBound === true时,说明返回的fBound被当做new的构造函数调用
                return self.apply(this instanceof fBound ? this : oThis, args.concat([].slice.call(arguments)))
            }
            var func = function(){}
            //维护原型关系
            if(this.prototype){
                func.prototype = this.prototype
            }
            //使fBound.prototype是func的实例,返回的fBound若作为new的构造函数,新对象的__proto__就是func的实例
            fBound.prototype = new func()
            return fBound
        }
    

    相关文章

      网友评论

          本文标题:call,apply.bind的实现原理

          本文链接:https://www.haomeiwen.com/subject/xskfrctx.html