bind

先看bind的源码

// The .bind method from Prototype.js 
Function.prototype.bind = function(){ 
  var fn = this, args = Array.prototype.slice.call(arguments), object = args.shift(); 
  return function(){ 
    return fn.apply(object, 
      args.concat(Array.prototype.slice.call(arguments))); 
  }; 
};

从上面的代码可以看得出来,这个函数首先是得到了调用bind的函数对象A引用(this),然后将将传入到bind的参数进行分解得到需要调用函数对象A的对象B(args.shift()),最后这个函数返回的是一个函数对象C,这个函数对象是改变函数对象A的this为B,然后将传入到这个函数对象C的参数与原本传入到bind的参数一同连接调用函数C。

看例子

var bar = function(){
    console.log(this.x);
}
var bar2 = function(a) {
    console.log(this.x);
    console.log(a);
}
var foo = {
x:3
}
bar(); // undefined
var func = bar.bind(foo); //返回的只是函数对象
func(); // 3
var func2 = bar.bind(foo); //只是函数对象
var func3 = bar.bind(foo)("a"); //通过返回的函数对象调用了函数;
//也可以
var func4 = bar.bind(foo, "a")();

通过上面的func4来理解最上面的那段话,函数对象A,,也就是fn就是批bar这个函数对象;对象B是指foo, 返回的函数对象C是指bar.bind(foo);

原文地址:https://www.cnblogs.com/kinthon/p/4967907.html