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
optimizeCb内部优化函数接收参数:原始函数、执行上下文、参数个数。
【注:为什么说是内部优化函数,具体可以参考最下方参考文献详解:Why is call so much faster than apply?】
简而言之就是call比apply快的原因就是在call内部执行中,内部处理所需要的参数都是格式化好的参数,不用特殊处理。 optimizeCb源码:
// Internal function that returns an efficient (for current engines) version// of the passed-in callback, to be repeatedly applied in other Underscore// functions.// 内部优化方法,参数:函数,执行上下文,参数个数// 返回根据传入函数在不同执行上下文,不同参数个数的情况下执行的函数varoptimizeCb=function(func,context,argCount){// 如果没有指定执行上下文,返回该函数if(context===void0)returnfunc;switch(argCount){case1:
returnfunction(value){returnfunc.call(context,value);};// The 2-parameter case has been omitted only because no current consumers made use of it.// 针对下面的null的问题,已经在github提交了pull request(https://github.com/jashkenas/underscore/pull/2732),我认为应该是undefined而非null,具体在下面分析中会提到// case void 0:casenull:
// 在执行上下文中,没有参数个数,执行下面// 在undefined情况下_.each(), _.map()内部用到case3:
returnfunction(value,index,collection){returnfunc.call(context,value,index,collection);};// _.reduce(), _.reduceRight()case4:
returnfunction(accumulator,value,index,collection){returnfunc.call(context,accumulator,value,index,collection);};}// 其实不用上面的 switch-case 语句,直接执行下面的 return 函数就行了// 理由就是充分利用了call的参数格式化优化returnfunction(){returnfunc.apply(context,arguments);};};
underscore中optimizeCb优化函数
optimizeCb
内部优化函数接收参数:原始函数、执行上下文、参数个数。【注:为什么说是内部优化函数,具体可以参考最下方参考文献详解:Why is call so much faster than apply?】
简而言之就是
call
比apply
快的原因就是在call内部执行中,内部处理所需要的参数都是格式化好的参数,不用特殊处理。optimizeCb
源码:实例:
解析:
对于
_.each()
方法,案例中的context
是window
对象,argCount
为undefined
,如果此处按照null
的话则直接执行最后通用返回调用,不会进入case 3
的情况,但按照该优化函数设立目的应该是要进入该条件执行,可以参考1.8.2
版本[optimizeCb] Combine null and 3 as multi-case for argCount switch statement #2613,已提交pull request
:undefined【大家觉得呢???】按这样理解则执行
【参考文献】
The text was updated successfully, but these errors were encountered: