Skip to main content

bind原理

call、apply都可以指定函数的this指向。call接受的是若干个参数列表,apply接受一个包含多个参数的数组。
bind有以下特性:

  • 可以指定this
  • 返回一个函数
  • 可以传入参数
  • 偏函数应用

bind实现细节

  • 指定this
  • 返回函数
  • 合并两次函数的参数(偏函数应用)
  • 可以应用其他this绑定规则
  • 抛出异常
//bind实现
Function.prototype.myBind = function(conotext){
if(typeof this !== 'function'){
throw new Error('Function.prototype.myBind not a function');
}

const fn = this;

const curried = [].slice.call(arguments, 1);

const bound = function(){
const args = [].slice.call(arguments, 0);
context = this instanceof bound ? this : context;
return fn.apply(context, currie.concat(args));
})

const fNOP = function(){};

//借用中间函数传递调用函数的原型,实现了原型链继承,同事不会修改继承的原型即fn
fNOP.prototype = fn.prototype;
bound.prototype = new fNOP();

return bound;
}