Javascript实现call,bind,apply的代码怎么写
这篇文章主要介绍了Javascript实现call,bind,apply的代码怎么写的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Javascript实现call,bind,apply的代码怎么写文章都会有所收获,下面我们一起来看看吧。
1.检查当前调用的是否为函数
2.如果当前没有传入指向的this,则赋值为window
3.将fn指向当前调用的函数
4.获取传入的参数
5.将参数传入fn进行调用
6.将对象上的fn删除
7.返回结果
//普通call的实现functionhello(){console.log('hello我是'+this.name);};letperson={name:'krys'};varname='liang';//只有var的变量属于windowhello();//'hello我是liang'hello.call(person);//'hello我是krys'hello.call();//'hello我是liang'letperson2={name:'lwl'}Function.prototype.mycall=function(context){//不传入参数的时候,默认为windowif(typeofthis!=="function"){thrownewTypeError('Error');}context=context||window;context.fn=this;//fn就是上面的hello方法constargs=[...arguments].slice(1);//第一个参数不要constresult=context.fn(...args);//把剩下的其他参数传给hellodeletecontext.fn;returnresult;}hello.mycall(person2);
functiongetParams(){console.log('我是',this.name,'获取一些参数',...arguments);}letperson3={name:'hhh'};getParams.apply(person3,['hello','world'])Function.prototype.myApply=function(context){if(typeofthis!=="function"){thrownewTypeError()}context=context||window;context.fn=this;letresult;if(arguments[1]){//如果有传入参数数组console.log(arguments[1])result=context.fn(...arguments[1]);}else{result=context.fn();}deletecontext.fn;returnresult;}getParams.myApply({name:'llll'},['jjj','kkkk','llll']);
functiongetParams(){console.log('我是',this.name,'获取一些参数',...arguments);}letperson3={name:'hhh'};letperson4={name:'tttt'};getParams.bind(person3,'hello','world')getParams.bind(person4,'hello','world')('jjj','kkk');Function.prototype.myBind=function(context){if(typeofthis!=="function"){thrownewTypeError()}context=context||window;const_that=this;constargs=[...arguments].slice(1);returnfunctionF(){if(thisinstanceofF){returnnew_that(...args,...arguments);//这里的arguments是上面的jjjkkk}return_that.apply(context,args.concat(...arguments));//这里的arguments是上面的jjjkkk}}getParams.myBind({name:'llll'},'jjj','kkkk','llll')('hhhhllll');
关于“Javascript实现call,bind,apply的代码怎么写”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Javascript实现call,bind,apply的代码怎么写”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。