Javascript中的bind详解
前言
用过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是什么。从上面的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
因此可以得出结论1:
1、bind是Functoin原型链中Function.prototype的一个属性,每个函数都可以调用它。
2、bind本身是一个函数名为bind的函数,返回值也是函数,函数名是bound。(打出来就是bound加上一个空格)。
知道了bind是函数,就可以传参,而且返回值'bound '也是函数,也可以传参,就很容易写出例子2:
后文统一 bound 指原函数original bind之后返回的函数,便于说明。
var obj = {
name: '轩辕Rowboat',
};
function original(a, b){
console.log(this.name);
console.log([a, b]);
return false;
}
var bound = original.bind(obj, 1);
var boundResult = bound(2); // '轩辕Rowboat', [1, 2]
console.log(boundResult); // false
console.log(original.bind.name); // 'bind'
console.log(original.bind.length); //
console.log(original.bind().length); // 2 返回original函数的形参个数
console.log(bound.name); // 'bound original'
console.log((function(){}).bind().name); // 'bound '
console.log((function(){}).bind().length); //
由此可以得出结论2:
1、调用bind的函数中的this指向bind()函数的第一个参数。
2、传给bind()的其他参数接收处理了,bind()之后返回的函数的参数也接收处理了,也就是说合并处理了。
3、并且bind()后的name为bound + 空格 + 调用bind的函数名。如果是匿名函数则是bound + 空格。
4、bind后的返回值函数,执行后返回值是原函数(original)的返回值。
5、bind函数形参(即函数的length)是1。bind后返回的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: '轩辕Rowboat',
};
function original(a, b){
console.log(this.name);
console.log([a, b]);
}
var bound = original.bindFn(obj, 1);
bound(2); // '轩辕Rowboat', [1, 2]
如果面试官看到你答到这里,估计对你的印象60、70分应该是会有的。 但我们知道函数是可以用new来实例化的。那么bind()返回值函数会是什么表现呢。
接下来看例子3:
var obj = {
name: '轩辕Rowboat',
};
function original(a, b){
console.log('this', this); // original {}
console.log('typeof this', typeof this); // object
this.name = b;
console.log('name', this.name); //
console.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/create
function 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, 'Rowboat'); // 不抛出错误,且执行了。
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, 'Rowboat');
console.log(student2, 'student2', notAStudent2, 'notAStudent2'); // 抛出错误
细心的同学可能会发现了这版本的代码没有实现bind后的bound函数的nameMDN Function.name和lengthMDN Function.length。面试官可能也发现了这一点继续追问,如何实现,或者问是否看过es5-shim的源码实现L201-L335。如果不限ES版本。其实可以用ES5的
Object.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、bind是Function原型链中的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;
}
参考
OshotOkill翻译的 深入理解ES6 简体中文版 - 第三章 函数(虽然笔者是看的纸质书籍,但推荐下这本在线的书)
MDN Function.prototype.bind
冴羽: JavaScript深入之bind的模拟实现
《react状态管理与同构实战》侯策:从一道面试题,到“我可能看了假源码”
关于
作者:常以轩辕Rowboat为名混迹于江湖。前端路上 | PPT爱好者 | 所知甚少,唯善学。
转载自https://juejin.im/post/5bec4183f265da616b1044d7
Javascript中的bind详解的更多相关文章
- JavaScript正则表达式详解(二)JavaScript中正则表达式函数详解
二.JavaScript中正则表达式函数详解(exec, test, match, replace, search, split) 1.使用正则表达式的方法去匹配查找字符串 1.1. exec方法详解 ...
- (转)javascript中event对象详解
原文:http://jiajiale.iteye.com/blog/195906 javascript中event对象详解 博客分类: javaScript JavaScriptCS ...
- 【JavaScript中的this详解】
前言 this用法说难不难,有时候函数调用时,往往会搞不清楚this指向谁?那么,关于this的用法,你知道多少呢? 下面我来给大家整理一下关于this的详细分析,希望对大家有所帮助! this指向的 ...
- JavaScript中的this详解
前言 this用法说难不难,有时候函数调用时,往往会搞不清楚this指向谁?那么,关于this的用法,你知道多少呢? 下面我来给大家整理一下关于this的详细分析,希望对大家有所帮助! this指向的 ...
- Javascript中prototype属性详解 (存)
Javascript中prototype属性详解 在典型的面向对象的语言中,如java,都存在类(class)的概念,类就是对象的模板,对象就是类的实例.但是在Javascript语言体系中,是不 ...
- JavaScript 中 this 的详解
this 的指向 this 是 js 中定义的关键字,它自动定义于每一个函数域内,但是它的指向却让人很迷惑.在实际应用中,this 的指向大致可以分为以下四种情况. 原文作者:林鑫,作者博客:http ...
- javascript中this关键字详解
不管学习什么知识,习惯于把自己所学习的知识列成一个list,会有助于我们理清思路,是一个很好的学习方法.强烈推荐. 以下篇幅有点长,希望读者耐心阅读. 以下内容会分为如下部分: 1.涵义 1.1:th ...
- JavaScript中的arguments详解
1. arguments arguments不是真正的数组,它是一个实参对象,每个实参对象都包含以数字为索引的一组元素以及length属性. (function () { console.log(ar ...
- javascript中的操作符详解1
好久没有写点什么了,根据博主的技术,仍然写一点javascript新手入门文章,接下来我们一起来探讨javascript的操作符. 一.前言 javascript中有许多操作符,但是许多初学者并不理解 ...
随机推荐
- [bug] JS sort 函数在 ios 中无效
首先,请原谅我做一次标题党: 但我觉得从发现问题到最后解决问题的过程还是蛮有意思的,特此记录一下: 背景 近两天开发的航班延误宝是内嵌在客户端(android.ios)webview 中的 H5 页面 ...
- html5 页面基本骨架
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http ...
- 【wireshark】插件开发(一):概述
1. 概述 wireshark提供了灵活的插件机制,使用户可以方便地扩展wireshark的功能.插件的功能主要包括,但不限于协议解析器. 可以使用Lua或C语言来编写Wireshark插件,下表对比 ...
- vue的无缝滚动插件vue-seamless-scroll的安装与使用
npm安装地址 https://www.npmjs.com/package/vue-seamless-scroll 命令行执行: npm install vue-seamless-scroll --s ...
- 【BZOJ2082】【POI2010】Divine divisor 假的pollard-rho
题目大意:给你$m$个数$a_i$,定义$n=\Pi_{i=1}^{m}a_i$.将$n$分解质因数为$\Pi p_i^{k_i} $,$p_i$是质数.请输出$2^{max(k_i)}-1$,以及存 ...
- 【pkuwc2018】 【loj2537】 Minmax DP+线段树合并
今年年初的时候参加了PKUWC,结果当时这一题想了快$2h$都没有想出来.... 哇我太菜啦.... 昨天突然去搜了下哪里有题,发现$loj$上有于是就去做了下. 结果第一题我5分钟就把所有细节都想好 ...
- expect中使用exec执行shell命令
今天想在expect脚本中获取本机ip,执行脚本是报错,脚本如下: set localip [exec ifconfig eth0 | grep Mask | cut -d: -f2 | awk '{ ...
- Java之IO(七)ObjectInputStream和ObjectOutputStream
转载请注明源出处:http://www.cnblogs.com/lighten/p/7003536.html 1.前言 本章介绍Java字节流中重要的成员,对象流ObjectInputStream和O ...
- Zookeeper--0100--简介说明
1.1-Zookeeper简介 什么是Zookeeper? Zookeeper是一个高效的分布式协调服务,它暴露了一些公共服务,比如命名/配置/管理/同步控制/群组服务等.我们可以使用ZK来实现比如达 ...
- mybatis的小问题记录
mybatis的小问题记录 问题描述:mybaitis中的if判断字符串的时候错误写法如下(刚开始没发现): <if test="placeType='2'"> sql ...