bind源码解析

来源:互联网 发布:java中文乱码怎么解决 编辑:程序博客网 时间:2024/06/01 09:41

下面是bind函数的Polyfill源码

if (!Function.prototype.bind) {  Function.prototype.bind = function (oThis) {    if (typeof this !== "function") {      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");    }    var aArgs = Array.prototype.slice.call(arguments, 1),         fToBind = this,         fNOP = function () {},        fBound = function () {          return fToBind.apply(this instanceof fNOP                                 ? this                                 : oThis || this,                               aArgs.concat(Array.prototype.slice.call(arguments)));        };    fNOP.prototype = this.prototype;    fBound.prototype = new fNOP();    return fBound;  };}

这个函数有两点比较重要的地方
1.把bind返回的函数的prototyoe属性指向一个由匿名函数生成的对象,并且最终会执行原来的那个函数的prototype,也就是x.bind时的x,这里我觉得是为了说明bind返回的对象应该是原函数的一个副本,区别只是绑定了this和参数。
2.bind返回的匿名函数里的函数代码,其中apply的第一个参数
(this instanceof fNOP && oThis )? this : oThis,直接执行bind返回的函数时,this instanceof fNOP返回false,所以apply的第一个参数是执行bind的时候的第一个参数,这也是平时我们的用法,但是如果是用new去执行bind返回的函数时,this instanceof fNOP返回的是true,这时候,如果在执行bind的时候传入了非空的值,那么这个值就会被新的this覆盖,如果传了空的值,那就把这个空值传给apply。说实话这里没看出作者的用意。。。。

补:this instanceof fNOP ? this : oThis || this这是另一个实现中的代码,相比之前的,我觉得这个更准确,这个说的是如果是new调用的时候,直接把执行bind时传入的this覆盖掉,这说明new执行时的this优先级更高,如果是直接执行而不是new调用时,就先判断执行bind时有没有传入this,如果有就把他压入x.bind中的x中执行,如果没有就传入新的this。

0 0