重构call,apply,bind

33 阅读1分钟

重构call

 Function.prototype._call=function(thisArg,...arg){

            // thisArg

            // console.log(this.name)

            // thisArg就是o对象

            // this就是当前调用_call这个方法的函数,也就是fn

            // this.name 就是"fn"

            // 给o对象添加一个键名叫做fn,并且这个方法是fn函数

            thisArg[this.name]=this;

            // Object.defineProperty(thisArg.__proto__,this.name,{

            //     configurable:true,

            //     value:this

            // })

            // console.log(thisArg[this.name])

            // 当执行这个函数时,这个函数的里面的this就变成的thisArg对象

           var result= thisArg[this.name](...arg);

           delete thisArg[this.name];

           return result

        }




        fn._call(o,1,2)
        

重构apply

Function.prototype._apply=function(thisArg,argArray){

            thisArg[this.name]=this;

            var result=thisArg[this.name](...argArray);

            delete thisArg[this.name];

            return result;

        }


        fn._apply(o,[1,2])
        

重构bind

    Function.prototype._bind=function(thisArg,...arg){

            // this 就是fn

            var f=this;

            return function(){

              return  f.apply(thisArg,arg.concat(...arguments))

            }

        }




        var f=fn.bind(o,1);

        f(2)