• 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也可以按相同思路来写

  • 相关阅读:
    UNITY 多个子MESH与贴图的对应关系
    UNITY 优化之带Animator的Go.SetActive耗时问题,在手机上,这个问题似乎并不存在,因为优化了后手机上运行帧率并未明显提升
    发现一个好办法-有问题可以到UNITY论坛搜索
    静态函数造成GC的原因
    关于GC.Collect在不同机器上表现不一致问题
    VULKAN学习资料收集
    Array.Resize(ref arry, size);
    玩游戏消耗精力
    浮点数与定点数问题
    P8 Visible Lattice Points
  • 原文地址:https://www.cnblogs.com/zimengxiyu/p/14639373.html
Copyright © 2020-2023  润新知