可以点击上方的话题JS基础系列,查看往期文章

写于2018年11月21日,发布在掘金阅读量1.3w+

前言

这是面试官问系列的第二篇,旨在帮助读者提升JS基础知识,包含new、call、apply、this、继承相关知识。
面试官问系列文章如下:感兴趣的读者可以点击阅读。
1.面试官问:能否模拟实现JS的new操作符
2.面试官问:能否模拟实现JS的bind方法(本文)
3.面试官问:能否模拟实现JS的call和apply方法
4.面试官问:JS的this指向
5.面试官问:JS的继承

用过React的同学都知道,经常会使用bind来绑定this

import React, { Component } from 'react';
class TodoItem extends Component{constructor(props){super(props);this.handleClick = this.handleClick.bind(this);}handleClick(){console.log('handleClick');}render(){return  (<div onClick={this.handleClick}>点击</div>);};
}
export default TodoItem;

那么面试官可能会问是否想过bind到底做了什么,怎么模拟实现呢。

附上之前写文章写过的一段话:已经有很多模拟实现bind的文章,为什么自己还要写一遍呢。学习就好比是座大山,人们沿着不同的路登山,分享着自己看到的风景。你不一定能看到别人看到的风景,体会到别人的心情。只有自己去登山,才能看到不一样的风景,体会才更加深刻。

先看一下bind是什么。从上面的React代码中,可以看出bind执行后是函数,并且每个函数都可以执行调用它。眼见为实,耳听为虚。读者可以在控制台一步步点开例子1中的obj:

var obj = {};
console.log(obj);
console.log(typeof Function.prototype.bind); // function
console.log(typeof Function.prototype.bind());  // function
console.log(Function.prototype.bind.name);  // bind
console.log(Function.prototype.bind().name);  // bound

Function.prototype.bind

因此可以得出结论1:

1、bindFunctoin原型链中Function.prototype的一个属性,每个函数都可以调用它。
2、bind本身是一个函数名为bind的函数,返回值也是函数,函数名是bound。(打出来就是bound加上一个空格)。知道了bind是函数,就可以传参,而且返回值'bound '也是函数,也可以传参,就很容易写出例子2
后文统一 bound 指原函数original bind之后返回的函数,便于说明。

var obj = {name: '若川',
};
function original(a, b){console.log(this.name);console.log([a, b]);return false;
}
var bound = original.bind(obj, 1);
var boundResult = bound(2); // '若川', [1, 2]
console.log(boundResult); // false
console.log(original.bind.name); // 'bind'
console.log(original.bind.length); // 1
console.log(original.bind().length); // 2 返回original函数的形参个数
console.log(bound.name); // 'bound original'
console.log((function(){}).bind().name); // 'bound '
console.log((function(){}).bind().length); // 0

由此可以得出结论2:

1、调用bind的函数中的this指向bind()函数的第一个参数。

2、传给bind()的其他参数接收处理了,bind()之后返回的函数的参数也接收处理了,也就是说合并处理了。

3、并且bind()后的namebound + 空格 + 调用bind的函数名。如果是匿名函数则是bound + 空格

4、bind后的返回值函数,执行后返回值是原函数(original)的返回值。

5、bind函数形参(即函数的length)是1bind后返回的bound函数形参不定,根据绑定的函数原函数(original)形参个数确定。

根据结论2:我们就可以简单模拟实现一个简版bindFn

// 第一版 修改this指向,合并参数
Function.prototype.bindFn = function bind(thisArg){if(typeof this !== 'function'){throw new TypeError(this + 'must be a function');}// 存储函数本身var self = this;// 去除thisArg的其他参数 转成数组var args = [].slice.call(arguments, 1);var bound = function(){// bind返回的函数 的参数转成数组var boundArgs = [].slice.call(arguments);// apply修改this指向,把两个函数的参数合并传给self函数,并执行self函数,返回执行结果return self.apply(thisArg, args.concat(boundArgs));}return bound;
}
// 测试
var obj = {name: '若川',
};
function original(a, b){console.log(this.name);console.log([a, b]);
}
var bound = original.bindFn(obj, 1);
bound(2); // '若川', [1, 2]

如果面试官看到你答到这里,估计对你的印象60、70分应该是会有的。但我们知道函数是可以用new来实例化的。那么bind()返回值函数会是什么表现呢。
接下来看例子3

var obj = {name: '若川',
};
function original(a, b){console.log('this', this); // original {}console.log('typeof this', typeof this); // objectthis.name = b;console.log('name', this.name); // 2console.log('this', this);  // original {name: 2}console.log([a, b]); // 1, 2
}
var bound = original.bind(obj, 1);
var newBoundResult = new bound(2);
console.log(newBoundResult, 'newBoundResult'); // original {name: 2}

例子3种可以看出this指向了new bound()生成的新对象。

可以分析得出结论3:

1、bind原先指向obj的失效了,其他参数有效。

2、new bound的返回值是以original原函数构造器生成的新对象。original原函数的this指向的就是这个新对象。另外前不久写过一篇文章:面试官问:能否模拟实现JS的new操作符。简单摘要:new做了什么:

1.创建了一个全新的对象。
2.这个对象会被执行[[Prototype]](也就是__proto__)链接。
3.生成的新对象会绑定到函数调用的this。
4.通过new创建的每个对象将最终被[[Prototype]]链接到这个函数的prototype对象上。
5.如果函数没有返回对象类型Object(包含Functoin, Array, Date, RegExg, Error),那么new表达式中的函数调用会自动返回这个新的对象。

所以相当于new调用时,bind的返回值函数bound内部要模拟实现new实现的操作。话不多说,直接上代码。

// 第三版 实现new调用
Function.prototype.bindFn = function bind(thisArg){if(typeof this !== 'function'){throw new TypeError(this + ' must be a function');}// 存储调用bind的函数本身var self = this;// 去除thisArg的其他参数 转成数组var args = [].slice.call(arguments, 1);var bound = function(){// bind返回的函数 的参数转成数组var boundArgs = [].slice.call(arguments);var finalArgs = args.concat(boundArgs);// new 调用时,其实this instanceof bound判断也不是很准确。es6 new.target就是解决这一问题的。if(this instanceof bound){// 这里是实现上文描述的 new 的第 1, 2, 4 步// 1.创建一个全新的对象// 2.并且执行[[Prototype]]链接// 4.通过`new`创建的每个对象将最终被`[[Prototype]]`链接到这个函数的`prototype`对象上。// self可能是ES6的箭头函数,没有prototype,所以就没必要再指向做prototype操作。if(self.prototype){// ES5 提供的方案 Object.create()// bound.prototype = Object.create(self.prototype);// 但 既然是模拟ES5的bind,那浏览器也基本没有实现Object.create()// 所以采用 MDN ployfill方案 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/createfunction Empty(){}Empty.prototype = self.prototype;bound.prototype = new Empty();}// 这里是实现上文描述的 new 的第 3 步// 3.生成的新对象会绑定到函数调用的`this`。var result = self.apply(this, finalArgs);// 这里是实现上文描述的 new 的第 5 步// 5.如果函数没有返回对象类型`Object`(包含`Functoin`, `Array`, `Date`, `RegExg`, `Error`),// 那么`new`表达式中的函数调用会自动返回这个新的对象。var isObject = typeof result === 'object' && result !== null;var isFunction = typeof result === 'function';if(isObject || isFunction){return result;}return this;}else{// apply修改this指向,把两个函数的参数合并传给self函数,并执行self函数,返回执行结果return self.apply(thisArg, finalArgs);}};return bound;
}

面试官看到这样的实现代码,基本就是满分了,心里独白:这小伙子/小姑娘不错啊。不过可能还会问this instanceof bound不准确问题。上文注释中提到this instanceof bound也不是很准确,ES6 new.target很好的解决这一问题,我们举个例子4:

instanceof 不准确,ES6 new.target很好的解决这一问题

function Student(name){if(this instanceof Student){this.name = name;console.log('name', name);}else{throw new Error('必须通过new关键字来调用Student。');}
}
var student = new Student('若');
var notAStudent = Student.call(student, '川'); // 不抛出错误,且执行了。
console.log(student, 'student', notAStudent, 'notAStudent');function Student2(name){if(typeof new.target !== 'undefined'){this.name = name;console.log('name', name);}else{throw new Error('必须通过new关键字来调用Student2。');}
}
var student2 = new Student2('若');
var notAStudent2 = Student2.call(student2, '川');
console.log(student2, 'student2', notAStudent2, 'notAStudent2'); // 抛出错误

细心的同学可能会发现了这版本的代码没有实现bind后的bound函数的nameMDN Function.name和lengthMDN Function.length。面试官可能也发现了这一点继续追问,如何实现,或者问是否看过es5-shim的源码实现L201-L335。如果不限ES版本。其实可以用ES5Object.defineProperties来实现。

Object.defineProperties(bound, {'length': {value: self.length,},'name': {value: 'bound ' + self.name,}
});

es5-shim的源码实现bind

直接附上源码(有删减注释和部分修改等)

var $Array = Array;
var ArrayPrototype = $Array.prototype;
var $Object = Object;
var array_push = ArrayPrototype.push;
var array_slice = ArrayPrototype.slice;
var array_join = ArrayPrototype.join;
var array_concat = ArrayPrototype.concat;
var $Function = Function;
var FunctionPrototype = $Function.prototype;
var apply = FunctionPrototype.apply;
var max = Math.max;
// 简版 源码更复杂些。
var isCallable = function isCallable(value){if(typeof value !== 'function'){return false;}return true;
};
var Empty = function Empty() {};
// 源码是 defineProperties
// 源码是bind笔者改成bindFn便于测试
FunctionPrototype.bindFn = function bind(that) {var target = this;if (!isCallable(target)) {throw new TypeError('Function.prototype.bind called on incompatible ' + target);}var args = array_slice.call(arguments, 1);var bound;var binder = function () {if (this instanceof bound) {var result = apply.call(target,this,array_concat.call(args, array_slice.call(arguments)));if ($Object(result) === result) {return result;}return this;} else {return apply.call(target,that,array_concat.call(args, array_slice.call(arguments)));}};var boundLength = max(0, target.length - args.length);var boundArgs = [];for (var i = 0; i < boundLength; i++) {array_push.call(boundArgs, '$' + i);}// 这里是Function构造方式生成形参length $1, $2, $3...bound = $Function('binder', 'return function (' + array_join.call(boundArgs, ',') + '){ return binder.apply(this, arguments); }')(binder);if (target.prototype) {Empty.prototype = target.prototype;bound.prototype = new Empty();Empty.prototype = null;}return bound;
};

你说出es5-shim源码bind实现,感慨这代码真是高效、严谨。面试官心里独白可能是:你就是我要找的人,薪酬福利你可以和HR去谈下。

最后总结一下

1、bindFunction原型链中的Function.prototype的一个属性,它是一个函数,修改this指向,合并参数传递给原函数,返回值是一个新的函数。
2、bind返回的函数可以通过new调用,这时提供的this的参数被忽略,指向了new生成的全新对象。内部模拟实现了new操作符。
3、es5-shim源码模拟实现bind时用Function实现了length
事实上,平时其实很少需要使用自己实现的投入到生成环境中。但面试官通过这个面试题能考察很多知识。比如this指向,原型链,闭包,函数等知识,可以扩展很多。
读者发现有不妥或可改善之处,欢迎指出。另外觉得写得不错,可以点个赞,也是对笔者的一种支持。

文章中的例子和测试代码放在github中bind模拟实现 github。bind模拟实现 预览地址 F12看控制台输出,结合source面板查看效果更佳。

// 最终版 删除注释 详细注释版请看上文
Function.prototype.bind = Function.prototype.bind || function bind(thisArg){if(typeof this !== 'function'){throw new TypeError(this + ' must be a function');}var self = this;var args = [].slice.call(arguments, 1);var bound = function(){var boundArgs = [].slice.call(arguments);var finalArgs = args.concat(boundArgs);if(this instanceof bound){if(self.prototype){function Empty(){}Empty.prototype = self.prototype;bound.prototype = new Empty();}var result = self.apply(this, finalArgs);var isObject = typeof result === 'object' && result !== null;var isFunction = typeof result === 'function';if(isObject || isFunction){return result;}return this;}else{return self.apply(thisArg, finalArgs);}};return bound;
}

推荐阅读

我在阿里招前端,我该怎么帮你?(现在还可以加模拟面试群)
如何拿下阿里巴巴 P6 的前端 Offer
如何准备阿里P6/P7前端面试--项目经历准备篇
大厂面试官常问的亮点,该如何做出?
如何从初级到专家(P4-P7)打破成长瓶颈和有效突破
若川知乎问答:2年前端经验,做的项目没什么技术含量,怎么办?
若川知乎高赞:有哪些必看的 JS库?

末尾

你好,我是若川,江湖人称菜如若川,历时一年只写了一个学习源码整体架构系列~(点击蓝字了解我)

  1. 关注若川视野,回复"pdf" 领取优质前端书籍pdf,回复"1",可加群长期交流学习

  2. 我的博客地址:https://lxchuan12.gitee.io 欢迎收藏

  3. 觉得文章不错,可以点个在看呀^_^另外欢迎留言交流~

精选前端好文,伴你不断成长

若川原创文章精选!可点击

小提醒:若川视野公众号面试、源码等文章合集在菜单栏中间【源码精选】按钮,欢迎点击阅读,也可以星标我的公众号,便于查找

面试官问:能否模拟实现JS的bind方法(高频考点)相关推荐

  1. 面试官问:能否模拟实现JS的new操作符(高频考点)

    可以点击上方的话题JS基础系列,查看往期文章 这篇文章写于2018年11月05日,new模拟实现,Object.create是面试高频考点,之前发布在掘金有近2万人阅读,现在发布到公众号声明原创. 1 ...

  2. 面试官问:能否模拟实现JS的call和apply方法

    写于2018年11月30日,发布在掘金上阅读量近一万,现在发布到微信公众号申明原创.相对比较基础的知识,虽然日常开发可能用得比较少,各种源码中有很多call和apply,需要掌握. 前言 这是面试官问 ...

  3. 面试官问:JS的this指向

    写于2018年12月25日,发布在掘金上阅读量近一万,现在发布到微信公众号申明原创. 前言 这是面试官问系列的第四篇,旨在帮助读者提升JS基础知识,包含new.call.apply.this.继承相关 ...

  4. 面试官问:JS的继承

    原文作者若川,掘金链接:https://juejin.im/post/5c433e216fb9a049c15f841b 写于2019年2月20日,现在发到公众号声明原创,之前被<前端大全> ...

  5. 后处理程序文件大小的变量_【每日一题】(17题)面试官问:JS中事件流,事件处理程序,事件对象的理解?...

    关注「松宝写代码」,精选好文,每日一题 作者:saucxs | songEagle 2020,实「鼠」不易 2021,「牛」转乾坤 风劲潮涌当扬帆,任重道远须奋蹄! 一.前言 2020.12.23 立 ...

  6. js var是什么类型_面试官问你JS基本类型时他想知道什么?

    点击上方"IT平头哥联盟",选择"置顶或者星标" 一起进步- 面试的时候我们经常会被问答js的数据类型.大部分情况我们会这样回答包括: 1.基本类型(值类型或者 ...

  7. obj: object是什么意思_面试官问你JavaScript基本类型时他想知道什么?

    本文原载于SegmentFault专栏"前端小将" 整理编辑:SegmentFault 面试的时候我们经常会被问答js的数据类型.大部分情况我们会这样回答包括: 1.基本类型(值类 ...

  8. 面试官问:跨域请求如何携带cookie?

    大家好,我是若‍川.持续组织了6个月源码共读活动,感兴趣的可以点此加我微信 ruochuan12 参与,每周大家一起学习200行左右的源码,共同进步.同时极力推荐订阅我写的<学习源码整体架构系列 ...

  9. nodejs express use 传值_再也不怕面试官问你express和koa的区别了

    前言 用了那么多年的express.js,终于有时间来深入学习express,然后顺便再和koa2的实现方式对比一下. 老实说,还没看express.js源码之前,一直觉得express.js还是很不 ...

最新文章

  1. FPGA(5)数码管静态显示与动态显示
  2. time_t和字符串间的转化
  3. Linux下查看文件夹下文件个数
  4. 八大攻略破解高级口译阅读
  5. Visual Studio Code,这是要上天?
  6. Google Hangouts支持使用Firefox WebRTC
  7. SAP Spartacus Customizing CMS Components
  8. 深度学习之卷积神经网络(13)DenseNet
  9. SQL 创建随机时间的函数
  10. 读书笔记——计算机组成原理
  11. js模块封装示例_AngularJS模块教程示例
  12. python做一个微型美颜图片处理器,十行代码即可完成
  13. 基于JAVA的宠物网站的设计与实现
  14. Vue抽离公共方法并全局注册使用
  15. MFS分布式存储搭建
  16. m3u8视频下载转为mp4
  17. 在浏览器中打开shell,连接linux
  18. PS系列 -- 颜色替换
  19. ProcessingJoy —— 油画笔触【JAVA】
  20. 战略选址、渠道精耕,数说故事数智化地图助力零售行业高质量扩张

热门文章

  1. python每隔半个小时执行一次_一篇文章教你用Python抓取微博评论
  2. sqllite开发安卓项目_【兼职项目】预算3万开发无线温度电流传感,2万开发直流电机打磨机控制...
  3. [No0000E6]C# 判断与循环
  4. Eclipse基金会
  5. Ajax 的乱码问题(2)
  6. linux 安装nginx php mysql 配置文件在哪_linux下 php+nginx+mysql安装配置
  7. cop2000计算机组成原理,COP2000计算机组成原理实验系统
  8. Ubuntu识别USB设备
  9. python until语句_详解Lua中repeat...until循环语句的使用方法
  10. jps显示当前所有java进程pid