有了对call()、apply()的前提分析,相信bind()我们也可以手到擒来。

参考前两篇:'对call()函数的分析' 和 '对apply()函数的分析',我们可以先得到以下代码:

Function.prototype.myBind = function(obj){
  // 判断调用对象是否为函数
  if(typeof this !== 'function'){
    console.error('type error!')
  }
  // 判断绑定的对象
  obj = obj || window;
}

bind()函数与call()函数参数的格式相同,不同的是bind()返回的是一个函数。

Function.prototype.myBind = function(obj){
  if(typeof this !== 'function'){
    console.error('type error!')
  }
  obj = obj || window;
  // 获取正确参数
  let args = [...arguments].slice(1);
  // 返回函数
  return function Fn(){};
}

使用bind()函数来对this进行绑定,可以之间在内部使用 apply() 。

Function.prototype.myBind = function(obj){
  if(typeof this !== 'function'){
    console.error('type error!')
  }
  obj = obj || window;
  let args = [...arguments].slice(1);
  return function Fn(){
    // 直接使用apply()
    return this.apply();
};
}

这个时候会发现,我们绑定的this是window,而不是我们想要的’this‘环境,可以使用that作为中间量。

Function.prototype.myBind = function(obj){
  if(typeof this !== 'function'){
    console.error('type error!')
  }
  obj = obj || window;
  // 在这里借助that
  that = this;
  let args = [...arguments].slice(1);
  return function Fn(){
    return that.apply();
};
}

然后我们需要考虑apply()中传递的参数,这里我们使用数组的concat()方法,得到apply中传递的数组。

Function.prototype.myBind = function(obj){
  if(typeof this !== 'function'){
    console.error('type error!')
  }
  obj = obj || window;
  that = this;
  let args = [...arguments].slice(1);
  return function Fn(){
// 传递两个参数(绑定对象,数组)
    return that.apply(obj,args.concat(...arguments));
};
}

最后需要判断函数作为构造函数的情况,这个时候需要传入当前函数的 this 给 apply 调用,其余情况都传入指定的上下文对象。

Function.prototype.myBind = function(obj){
  if(typeof this !== 'function'){
    console.error('type error!')
  }
  obj = obj || window;
  that = this;
  let args = [...arguments].slice(1);
  return function Fn(){
// 根据调用方式,传入不同绑定值
    return that.apply(
      this instanceof Fn ? this : obj,
      args.concat(...arguments));
};
}

最后通过一个例子,来验证是否达到bind()的功能要求。

Function.prototype.myBind = function(obj){
  if(typeof this !== 'function'){
    console.error('type error!')
  }
  obj = obj || window;
  that = this;
  let args = [...arguments].slice(1);
  return function Fn(){
    return that.apply(
      this instanceof Fn ? this : obj,
      args.concat(...arguments)
    );
  }
}
let dog = {
  name: '狗',
  eat(food1, food2) {
    console.log(this.name + '爱吃' + food1 + food2);
  }
}
let cat = {
  name: '猫',
}
dog.eat.bind(cat, '鱼', '肉')(); // 猫爱吃鱼肉
dog.eat.mybind(cat, '鱼', '肉')(); // 猫爱吃鱼肉

理解并手写 bind() 函数的更多相关文章

  1. 理解并手写 call() 函数

    手写自己的call,我们要先通过call的使用,了解都需要完成些什么功能? call()进行了调用,是个方法,已知是建立在原型上的,使用了多个参数(绑定的对象+传递的参数). 我们把手写的函数起名为m ...

  2. 手写bind函数

    实现bind函数 参考MDN提供的Polyfill方案 Function.prototype.myBind = function(context){ //这里对调用者做一个判断,如果不是函数类型,直接 ...

  3. 理解并手写 apply() 函数

    apply()函数,在功能上类似于call(),只是传递参数的格式有所不同. dog.eat.call(cat, '鱼', '肉'); dog.eat.apply(cat, ['鱼', '肉']); ...

  4. 前端面试题整理——手写bind函数

    var arr = [1,2,3,4,5] console.log(arr.slice(1,4)) console.log(arr) Function.prototype.bind1 = functi ...

  5. WPF启动流程-自己手写Main函数

    WPF一般默认提供一个MainWindow窗体,并在App.Xaml中使用StartupUri标记启动该窗体.以下通过手写实现WPF的启动. 首先先介绍一下VS默认提供的App.Xaml的结构,如下图 ...

  6. 优雅手撕bind函数(面试官常问)

    优雅手撕bind函数 前言: 为什么面试官总爱让实现一个bind函数? 他想从bind中知道些什么? 一个小小的bind里面内有玄机? 今天来刨析一下实现一个bind要懂多少相关知识点,也方便我们将零 ...

  7. python 精华梳理(已理解并手写)--全是干货--已结

    基础部分 map,reduce,filter,sort,推导式,匿名函数lambda , 协程,异步io,上下文管理 自定义字符串转数字方法一不使用reduce import re def str2i ...

  8. C++之手写strlen函数

    代码: int strlen(const char *str){ assert(str!=NULL); intlen=; while((*str++)!='\0') len++; return len ...

  9. js面试题之手写节流函数和防抖函数

    函数节流:不断触发一个函数后,执行第一次,只有大于设定的执行周期后才会执行第二次 /* 节流函数:fn:要被节流的函数,delay:规定的时间 */ function throttle(fn,dela ...

随机推荐

  1. Redis为什么是单线程,高并发快的3大原因详解

    出处知乎:https://zhuanlan.zhihu.com/p/58038188 Redis的高并发和快速原因 1.redis是基于内存的,内存的读写速度非常快: 2.redis是单线程的,省去了 ...

  2. 无法加载 mcrypt (外链,英语) 扩展,请检查您的 PHP 配置。

    转载请注明来源:https://www.cnblogs.com/hookjc/ 需要安装libcrytp,在下面的地址下载libmarypt: ftp://mcrypt.hellug.gr/pub/c ...

  3. MyEclipse工程中Java Build Path中的JDK版本和Java Compiler Compiler compliance level的区别

    感谢大佬:https://blog.csdn.net/shan9liang/article/details/17266519 问题起源: 今天再在ESB调用WebService测试,需要在jboss上 ...

  4. iOS,蓝牙开发!!--By帮雷

    iOS的蓝牙开发大致有以下几种方式. 1 GameKit.framework [只能存在于iOS设备之间,多用于游戏 能搜索到的demo比较多,不确切说名字了,code4app里面就有] 2 Core ...

  5. JAVA! static的作用

    是静态修饰符,什么叫静态修饰符呢?大家都知道,在程序中任何变量或者代码都是在编译时由系统自动分配内存来存储的,而所谓静态就是指在编译后所分配的内存会一直存在,直到程序退出内存才会释放这个空间,也就是只 ...

  6. zabbix 监控系统概述及部署

    zabbix 监控系统概述及部署 1.Zabbix是什么: zabbix是一个个基于web界而的提供分布式系统监视以及网络监视功能的企业级的开源解决方案. zabbix能监视各种网络参数,保证服务器系 ...

  7. 4G无线全网通太阳能水文设备电源监测系统BMS110

    钡铼技术BMS110模块可实现4路电池电压.2路模拟量.2路数字量和1路温度测量,支持Modbus RTU over TCP和MQTT通讯协议,DC9-36V电源供电.BMS110可应用于各种有使用蓄 ...

  8. opencv笔记--Active contours

    Active Contours 也称作 Snake,通过定义封闭区域曲线的能量函数,并使其最小化得到最终曲线. Active Contours 被用作物体边界精确定位上,opencv 给出了一个实现, ...

  9. Solution -「Gym 102798I」Sean the Cuber

    \(\mathcal{Description}\)   Link.   给定两个可还原的二阶魔方,求从其中一个状态拧到另一个状态的最小步数.   数据组数 \(T\le2.5\times10^5\). ...

  10. 我们一起来学Shell - 正则表达式

    文章目录 什么是正则表达式 正则表达式元字符 正则表达式应用举例 POSIX 方括号表达式 POSIX 字符集列表: 我们一起来学Shell - 初识shell 我们一起来学Shell - shell ...