当前位置: 首页 > Web前端 > JavaScript

实现一个绑定方法

时间:2023-03-26 23:11:04 JavaScript

Function.prototype.myBind=function(){//保存this和this指向问候语letthat=this//this必须是一个函数bind必须绑定一个函数if(typeofthat!=='function'){thrownewTypeError('Function.prototype.bind-'+'whatistryingtobeboundisnotcallable')}//arguments是mybind传入的所有参数letthatArg=arguments[0]//我们需要绑定其余的参数,全部传入返回的函数//第一个参数已经被使用了,所以除了第一个参数letargs=Array.prototype外,args的值应该取下标1作为bind中的参数。slice.call(arguments,1)letFb=function(){//返回的函数中可能有参数,bind中的参数和return方法中的参数要合并//args是bind的参数//Array.prototype.slice.call(arguments,1)是当前返回函数的参数let_args=[...args,Array.prototype.slice.call(arguments)]//bind会创建一个新的绑定函数,也可以使用new运算符//判断Fb是否为新函数(){}if(that.prototype){fnop.prototype=that.prototype}Fb.prototype=newfnop()returnFb}varobj={name:'Smiley'}vargreeting=function(str,lang){this.value='greetingValue'console.log('Welcome'+this.name+'to'+str+'in'+lang)}varobjGreeting=greeting.myBind(obj,'世界')//objGreeting('JS');varnewObj=newobjGreeting('JS');console.log(newObj.value);