bind
概念
概念:方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。 语法:function.bind(thisArg[, arg1[, arg2[, …]]]) 参数: thisArg:调用绑定函数时作为 this 参数传递给目标函数的值。 如果使用new运算符构造绑定函数,则忽略该值。当使用 bind 在 setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind 函数的参数列表为空,或者thisArg是null或undefined,执行作用域的 this 将被视为新函数的 thisArg。 arg1, arg2, …:当目标函数被调用时,被预置入绑定函数的参数列表中的参数。 返回值:返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。
实现
- 判断调用者是否为函数。
 - 截取参数,注意:这里有两种形式传参。
 - 返回一个函数,判断外部哪种方式调用了该函数(new | 直接调用)
 
const module = {x:42,getX:function(){return this.x;}}const unboundGetX = module.getX;console.log(unboundGetX());console.log(unboundGetX.bind(module)())Function.prototype.myBind= function(context){// 判断调用者是否为函数if (typeof this !== 'function') {throw new TypeError('Error')}let args = [...arguments].slice(1)//_this指向调用函数const _this = this;return function F(){// 因为返回了一个函数,我们可以 new F(),所以需要判断// 对于 new 的情况来说,不会被任何方式改变 thisif(this instanceof F){return new _this(...args,...arguments)}else{return _this.apply(context,args.concat(...arguments))}}}console.log(unboundGetX.myBind(module)())
示例
- 创建绑定函数
 - 偏函数
 - 配合 setTimeout
 
