猿问

javascript关于bind方法的实现

bind是ECMA5中才出现的方法,IE8等低版本浏览器并不支持,所以在MDN中有了这样的一段代码:
if(!Function.prototype.bind){//如果低版本浏览器不支持bind
Function.prototype.bind=function(oThis){
if(typeofthis!=="function"){//如果this不是一个函数,抛出错误
//closestthingpossibletotheECMAScript5internalIsCallablefunction
thrownewTypeError("Function.prototype.bind-whatistryingtobeboundisnotcallable");
}
varaArgs=Array.prototype.slice.call(arguments,1),//arguments为bind()括号中的参数
fToBind=this,
fNOP=function(){},
fBound=function(){
returnfToBind.apply(thisinstanceoffNOP&&oThis
?this
:oThis||window,
aArgs.concat(Array.prototype.slice.call(arguments)));//argument为bind返回方法运行时候的参数
};
fNOP.prototype=this.prototype;
fBound.prototype=newfNOP();
returnfBound;
};
}
在理解的时候,加了一些注释。但是其他的一段代码不知道为什么(或者修补什么情况)存在:
fNOP=function(){}//只是为了单纯复制this的原型链?
thisinstanceoffNOP&&oThis?this:oThis||window//经测试,thisinstanceoffNO一直返回false,所以等价于oThis||window,那为什么存在?
fNOP.prototype=this.prototype;//?
fBound.prototype=newfNOP();//?
按照我的理解,觉得以下代码也可以满足需要:
if(!Function.prototype.bind){
Function.prototype.bind=function(oThis){
if(typeofthis!=="function"){
thrownewTypeError("bindfunctionerror");
}
varaArgs=Array.prototype.slice.call(arguments,1),
fToBind=this,
fBound=function(){
returnfToBind.apply(oThis||window,aArgs.concat(Array.prototype.slice.call(arguments)));
};
returnfBound;
};
}
下面测试代码,好使:
varobj={
name:'name1',
say:function(arg1,arg2){
console.log(this.name,arg1,arg2)
}
}
varfoo={
name:'name2'
}
obj.say.bind(foo,'必定显示1','必定显示2')('没有位置不显示了1','没有位置不显示了2')//name2必定显示1必定显示2
能给个比较清楚的解释吗?
米脂
浏览 398回答 2
2回答
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答