JavaScript手写bind函数

函数是有Function构建出来的,它本身是内有bind函数的,要手写bind函数可以写到Function.prototype上,这里用到了,原型链,this,call,apply,arguments,slice等知识。过程分为三步。

一、首先在Function.prototype写个bind1函数(为了不覆盖原有的bind函数),用arguments来接受参数,arguments可以接受所有的参数,不写它也可以接收到。这里用slice方法来把arguments变成数组,【slice(begin,end)不写标识从索引0开始一直找到末尾,并返回新的数组,call把this指向arguments,表示arguments借用slice查找返回新数组】

 Function.prototype.bind=function(){
            //把arguments转换成数组
            let arr=Array.prototype.slice.call(arguments)
}

二、bind,call,apply这些方法它第一个参数是要对this重新绑定的对象,所以要把第一个参数取出来(这里用shift来取,shift删除数组第一个元素,并返回该元素)。并把这个参数存起来,另外this也要存起来。

Function.prototype.bind=function(){
            console.log('arguments--',arguments);
            //把arguments转换成数组
            let arr=Array.prototype.slice.call(arguments)
            let t=arr.shift();
            let _this=this;

        }

三、原有的bind函数会创建一个新的函数,这里也返回一个新函数来处理,

 Function.prototype.bind=function(){
            console.log('arguments--',arguments);
            //把arguments转换成数组
            let arr=Array.prototype.slice.call(arguments)


            let t=arr.shift();
            let _this=this;
            return function(){
                return _this.apply(t,arr)
            }
        }

全部代码执行并调用:

        function fn(a,b,c){
            console.log('this---------',this);
            console.log('参数',a,b,c);
        }
        //bind函数
        Function.prototype.bind1=function(){
            console.log('arguments--',arguments);
            //把arguments转换成数组
            let arr=Array.prototype.slice.call(arguments)


            let t=arr.shift();
            let _this=this;
            return function(){
                return _this.apply(t,arr)
            }
        }
        let fn1=fn.bind1({x:100},10,20,30)
        console.log(fn1());

同理call,apply也可以按相同思路来写