underscore中源码optimizeCb如何理解?



 var optimizeCb = function(func, context, argCount) {
    if (context === void 0) return func;
    switch (argCount == null ? 3 : argCount) {
      case 1: return function(value) {
        return func.call(context, value);
      };
      case 2: return function(value, other) {
        return func.call(context, value, other);
      };
      case 3: return function(value, index, collection) {
        return func.call(context, value, index, collection);
      };
      case 4: return function(accumulator, value, index, collection) {
        return func.call(context, accumulator, value, index, collection);
      };
    }
    return function() {
      return func.apply(context, arguments);
    };
  };

上次同事说这段代码叫 偏函数 ,然后上网查了一些概念 http://www.vaikan.com/currying-partial-application/
之后又了解到 Higher-Order Functions,能否解释一下这些概念?以及上面的函数是不是偏函数?

underscore JavaScript

Cissa夹心 8 years, 9 months ago

这个之前讨论过。讨论的结果见这个链接:
关于underscore.js中optimizeCb函数中是否需要switch的问题

clipboard.png

技术型闷骚 answered 8 years, 9 months ago

其实你发的这段代码完全可以用下面这段来代替, 中间的那段 switch 完全是多余的.
switch 那段的唯一用处, 就是可以向你展示一个规范, 告诉你在传递几个参数的时候, 相应的参数什么是什么东东而已, 而这种东东, 完全可以写在注释里.


 var optimizeCb = function(func, context) {
    if (context === void 0) return func;
    return function() {
      return func.apply(context, arguments);
    };
  };

而这个方法用处等同于 bind .

clipboard.png

下面为不删除 switch 时的效果:

clipboard.png

--

关于 @iu2fish 截图中的内容:

clipboard.png

再加上所发连接中翻译的内容(注意红色圈的地方):

clipboard.png

与本代码中的 func.apply(context, arguments) 中用法 木有任何关系, 因为本代码中的用法并不影响引擎的优化.

所以关于截图中 说话的那个人对 switch 的描述是有误的.

故乡的茶干 answered 8 years, 9 months ago

Your Answer