zoukankan      html  css  js  c++  java
  • 手写一个简易的bind函数

     1 // bind方法 在构造函数的原型对象上
     2 // 接受的是逗号隔开的参数形式  参数的个数不确定
     3 Function.prototype.bind1 = function () {
     4   // 将 逗号隔开的参数分割成数组  arguments 可以获取所有的参数
     5   const args = Array.prototype.slice.call(arguments);
     6   //   从数组中删除传入的this指向 并返回  剩下的都是传入的参数 shift 从头部删除  返回删除的元素  把this剔除出去 剩下的都是参数  所以要用shift删除
     7   const _this = args.shift();
     8   //   谁调用bind1方法  this指向谁  当前函数的this指向
     9   const self = this;
    10   //   调用bind方法 的时候  返回一个函数
    11   return function () {
    12     //  函数内部通过apply 修改this指向并返回结果   (主要功能 是apply内部实现的)
    13     return self.apply(_this, args);
    14   };
    15 };
    16 // 定义一个fn1函数
    17 function fn1(a, b, c) {
    18   console.log("this", this);
    19   console.log(a, b, c);
    20   return "this is fn1";
    21 }
    22 // fn1通过bind修改this指向 返回一个新函数
    23 const fn2 = fn1.bind1({ x: 10 }, 10, 20, 30);
    24 // 调用 这个新函数
    25 const res = fn2();
    26 // 打印新函数的返回值
    27 console.log(res);
  • 相关阅读:
    动态规划突破
    日志如何进行处理
    多线程相关问题
    Activity工作流框架
    修改模块
    spring多模块搭建Eureka服务器端
    springcould多模块搭建Eureka的服务器端口
    java操作elecsearch
    在elementui和MyBatis中前后端分离中使用shiro
    elementui的和前后端分离的微信登陆功能
  • 原文地址:https://www.cnblogs.com/ndh074512/p/15368240.html
Copyright © 2011-2022 走看看