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
Functuin.prototype._call=function(context){if(typeofthis!=='function'){throwError('Function.prototype._call - what is trying to be bound is not callable')}context=context||window// 这里只考虑了浏览器中的实现context.fn=thisvarargs=[]varlen=arguments.lengthfor(vari=1;i<len;i++){args.push('arguments['+i+']')}varresult=eval('context.fn('+args+')')deletecontext.fnreturnresult}
模拟apply的实现
apply的模拟和call很类似,只是参数处理的时候有些不同。
Function.prototype._apply=function(context,args){if(typeofthis!=='function'){throwError('Function.prototype._apply - what is trying to be bound is not callable')}context=context||window// 这里只考虑了浏览器中的实现context.fn=thisvarresultif(!args){result=context.fn()}else{varlen=args.lengthvartmp=[]for(vari=0;i<len;i++){tmp.push('args['+i+']')}result=eval('context.fn('+tmp+')')}deletecontext.fnreturnresult}
模拟实现
call()
和apply()
call()
和apply()
都能够用来绑定this
到某个对象上,我们来模拟实现一下相同的功能。先看个例子
可以看到,通过对象的某个属性来调用函数时,该函数内部的
this
会指向当前对象。这样我们就有思路模拟call
和apply
。也就是说将调用call
或者apply
的函数保存在this
要绑定到的对象,然后通过该对象来调用函数就可以了。模拟
call
的实现做个测试
很简单,我们已经实现了简单的
call
的模拟,还有参数传递没有实现。call
接收的参数都是不固定的,从索引值第一个开始需要传递给调用的函数,而apply
则是将数组的每一项逐个传入调用函数。可以使用eval()
来执行这个函数来实现。继续做个测试
我们还记得,
call
可以传入null
和undefined
,这是this
会指向全局对象,再修改下我们的实现模拟
apply
的实现apply
的模拟和call
很类似,只是参数处理的时候有些不同。简单的测试一下
The text was updated successfully, but these errors were encountered: