underscore源码阅读

阅读来源 https://github.com/aircloud/underscore-analysis

该仓库中有非常详尽的underscore解析, 非常值得一看, 这里仅记录一些自己在意的地方

统一优化回调方式, 其中这种规范参数位置的方法在大项目里很值得人学习

var optimizeCb = function(func, context, argCount) {
      // 如果没有指定 this 指向,则返回原函数
      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);
        };
  ​
        // 如果有指定 this,但没有传入 argCount 参数
        // 则执行以下 case
        // _.each、_.map
        case 3: return function(value, index, collection) {
          return func.call(context, value, index, collection);
        };
  ​
        // _.reduce、_.reduceRight
        case 4: return function(accumulator, value, index, collection) {
          return func.call(context, accumulator, value, index, collection);
        };
      }
      return function() {
        return func.apply(context, arguments);
      };
    };

函数式编程的体现, 虽然a.length一下子就能得到结果了, 但是封装成一个函数的话更方便管理(而且这里有个优化, 检测了obj是否存在, 以免传入obj为null||undefined的值报错, 我的代码就经常在这里报错= =!)

var property = function(key) {
      return function(obj) {
        return obj == null ? void 0 : obj[key];
      };
    };
    // getLength 函数
    // 该函数传入一个参数,返回参数的 length 属性值
    // 用来获取 array 以及 arrayLike 元素的 length 属性值
    var getLength = property('length');
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。