zoukankan      html  css  js  c++  java
  • 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也可以按相同思路来写

  • 相关阅读:
    [noip2011d2t2]聪明的质检员 二分+前缀和优化
    [noip2016d2t2]蚯蚓
    KMP
    杨辉三角(二项式定理)&&组合数 【noip 2011/2016 d2t1】
    bzoj1615 [Usaco2008 Mar]The Loathesome Hay Baler麻烦的干草打包机
    [noip2015 pjt3]求和
    [周记]8.28~9.3
    [noip2011 d1t3] Mayan游戏
    react基础用法二(组件渲染)
    react基础用法一(在标签中渲染元素)
  • 原文地址:https://www.cnblogs.com/zimengxiyu/p/14639373.html
Copyright © 2011-2022 走看看