博客
关于我
手动实现bind函数(js)
阅读量:757 次
发布时间:2019-03-23

本文共 723 字,大约阅读时间需要 2 分钟。

手动实现bind函数

⭐ 实现步骤

  • 首先检查当前调用对象是否为函数
  • 保存第一个参数作为函数的执行上下文
  • 定义一个回调函数,将其作为bind方法的返回值
  • 使用箭头函数定义回调函数,确保this键保留原值
  • 继续接受和处理传入的参数,采用concat方法实现数组合并
  • 调用原函数:通过apply方法将this设定为指定的上下文
  • ⭐关键实现要点

    要实现bind函数需要以下几个关键点:

    1. 通过保存this实现上下文绑定

    2. 确保参数传递功能原封不动

    3. 调用目标函数时,正确设置this值

    ⭐示例实现代码

    Function.prototype.mybind=function(context]{     if(typeof this!=='function'){       throw new Error("this not a function");     }    var arr=Array.from(arguments).slice(1);     var mybound=function(){       arr=arr.concat(...arguments);       return this.apply(context,arr);     };     return mybound;   });

    ⭐实际应用示例

    定义一个对象:

    var obj={
    name:'lijia'
    };

    定义一个函数:

    function foo(age,pp){
    console.log(this.name,age,pp);
    }

    绑定函数并执行:

    foo.mybind(obj,20,30)()

    输出结果应为:

    ['lijia',20,30]

    转载地址:http://cfizk.baihongyu.com/

    你可能感兴趣的文章
    python3+django使用celery执行某些任务失败的解决方案
    查看>>
    Python3+Requests+Unittest实战系列【一】
    查看>>
    python3+requests+unittest实战系列【一】
    查看>>
    python3+requests+unittest实战系列【二】
    查看>>
    Python3+Requests+Unittest实战系列【二】
    查看>>
    python3----ASCII
    查看>>
    Python3-selenium自动化测试框架,结合HTMLTestRunner测试报告!
    查看>>
    Python3-如何自我更新作为服务运行的应用程序
    查看>>
    Python3.1-网格模拟概念性问题
    查看>>
    Python3.12 解决conda环境libstdc++版本过低问题
    查看>>
    python3.2批量查询IP地址区域
    查看>>
    Python3.5中协程和未来/任务之间的区别?
    查看>>
    python3.5实现socket通讯(TCP)
    查看>>
    python3.6 ubuntu部署nginx、 uwsgi、 django
    查看>>
    Python3.6.3中,functools似乎不能用
    查看>>
    python3.6.5+cuda9+cudnn7.1+win10+tensorflow-gpu1.9.0下载配置
    查看>>
    python3.6使用pickle序列化class
    查看>>
    python3.6入门到高阶(全栈) day027 网络通信协议 osi七层模型
    查看>>
    Python3.6属性错误:模块‘;异步没有属性‘;运行‘;
    查看>>
    python3.6版本中的python-weka-wrapper安装失败,错误代码为%1
    查看>>