外部函数接收三个参数,里面的函数只需要一个参数或者需要四个参数的时候,里面的函数的参数怎么被赋值的?

  var optimizeCb = function(func, context, argCount) {
    // 如果没有指定 this 指向,则返回原函数
    if (context === void 0) return func;

    switch (argCount == null ? 3 : argCount) {
      case 1: return function(value) {                        //这里的value从哪里来的
        return func.call(context, value);       
      };
      case 2: return function(value, other) {                 //这里的other从哪里来的
        return func.call(context, value, other);  
      };

      // 如果有指定 this,但没有传入 argCount 参数
      // 则执行以下 case
      // _.each、_.map
      case 3: return function(value, index, collection) {     //还有这里的index,collection
        return func.call(context, value, index, collection);
      };

      // _.reduce、_.reduceRight
      case 4: return function(accumulator, value, index, collection) {    //这里的accumulator
        return func.call(context, accumulator, value, index, collection);
      };
    }
    return function() {
      return func.apply(context, arguments);
    };
  };
阅读 3.6k
3 个回答

这不就是闭包吗,当你调用外层函数的时候,返回了一个新的函数,然后你再给返回的函数传值

例如:

 function fn1(a){
   return function(b){
     console.log(a+b)
   }
 }
 
 var fn2 = fn1('hello') //这时候的值是返回的函数
 fn2('world') //这时候执行里面的函数 得到 helloworld

optimizeCb返回了一个函数,你有疑问的那些参数会在这个返回的函数调用的时候传入的。

那是被return的函数的形参,调用的时候传实参才用的上。
比如:

function fun1(a){
    return function fun2(b){
        console.log('b: ',b);
        }
}
fun1(1);
fun1(1)(2);

你运行下就懂了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题