You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
if(!Function.prototype.bind){Function.prototype.bind=function(oThis){if(typeofthis!=="function"){// closest thing possible to the ECMAScript 5 internal IsCallable functionthrownewTypeError("Function.prototype.bind - what is trying to be bound is not callable");}varaArgs=Array.prototype.slice.call(arguments,1),fToBind=this,fNOP=function(){},fBound=function(){// this instanceof fBound === true时,说明返回的fBound被当做new的构造函数调用returnfToBind.apply(thisinstanceoffBound
? this
: oThis||window,aArgs.concat(Array.prototype.slice.call(arguments)));};fNOP.prototype=this.prototype;fBound.prototype=newfNOP();returnfBound;};}
实现bind要做什么
第一个是参数,agruments的使用
这里是将bind函数的参数数组取出来,第一个参数不要(就是不要oThis)也就是要被绑定方法的那个对象,第二个是
这里是用了数组的方法,把参数插在参数数组后面,要注意,这个函数是要被return 出去然后执行的,他的参数数组是return出去的那个fBound函数的参数数组,所以上下两个参数数组是不一样的,有点像柯里化。
第二个是上下文,在其中上下文的变化比较难理解,bind函数主要就是为了绑定上下文来使用的
这里是保存了对象的上下文,紧接着下面的apply方法让要被绑定的那个对象可以使用该上下文
这里是以fNOP为中介把this.prototype这个原对象的属性给fBound,确保fBound是在定义的时候的那个上下文里面执行。本来
就可以将原属性集成过来了,但是这样两个对象属性都指向同一个地方,修改
bound.prototype
将会造成self.prototype
也发生改变,这样并不是我们的本意。所以通过一个空函数nop
做中转,能有效的防止这种情况的发生。The text was updated successfully, but these errors were encountered: