关于原生js中bind函数的实现

今天继续研究了bind函数的实现,也知道了shim和polyfill的说法,现在总结一下,

 1 if (!Function.prototype.bind) {
 2   Function.prototype.bind = function (oThis) {
 3     if (typeof this !== "function") {
 4       // closest thing possible to the ECMAScript 5 internal IsCallable function
 5       throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
 6     }
 7 
 8     var aArgs = Array.prototype.slice.call(arguments, 1), 
 9         fToBind = this, 
10         fNOP = function () {},
11         fBound = function () {
12           return fToBind.apply(this instanceof fNOP && oThis
13                                  ? this
14                                  : oThis || window,
15                                aArgs.concat(Array.prototype.slice.call(arguments)));
16         };
17 
18     fNOP.prototype = this.prototype;
19     fBound.prototype = new fNOP();
20 
21     return fBound;
22   };
23 }

这是官方文档上的实现,我分二个方面来谈我要说的东西,

第一个是参数,agruments的使用

 var aArgs = Array.prototype.slice.call(arguments, 1),

这里是将bind函数的参数数组取出来,第一个参数不要(就是不要oThis)也就是要被绑定方法的那个对象,第二个是

aArgs.concat(Array.prototype.slice.call(arguments)));

 这里是用了数组的方法,把参数插在参数数组后面,要注意,这个函数是要被return 出去然后执行的,他的参数数组是return出去的那个fBound函数的参数数组,所以上下两个参数数组是不一样的,有点像柯里化。

第二个是上下文,在其中上下文的变化比较难理解,bind函数主要就是为了绑定上下文来使用的

 fToBind = this

 这里是保存了对象的上下文,紧接着下面的apply方法让要被绑定的那个对象可以使用该上下文

 fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

这里是以fNOP为中介把this.prototype这个原对象的属性给fBound,确保fBound是在定义的时候的那个上下文里面执行。本来

bound.prototype = self.prototype

就可以将原属性集成过来了,但是这样两个对象属性都指向同一个地方,修改 bound.prototype 将会造成self.prototype 也发生改变,这样并不是我们的本意。所以通过一个空函数 nop 做中转,能有效的防止这种情况的发生。

原文地址:https://www.cnblogs.com/admos/p/4455922.html