如果直接讲解源码,你可能想不明白为什么要这么写,所以我们从 _.map 函数开始讲起。

_.map

.map 类似于 ,但更加健壮和完善。我们看下 .map 的源码:

map 方法除了传入要处理的数组之外,还有两个参数 iteratee 和 context,类似于 Array.prototype.map 中的其他两个参数,其中 iteratee 表示处理函数,context 表示指定的执行上下文,即 this 的值。

然后在源码中,我们看到,我们将 iteratee 和 context 传入一个 cb 函数,然后覆盖掉 iteratee 函数,然后将这个函数用作最终的处理函数。

实际上,需要这么麻烦吗?不就是使用 iteratee 函数处理每次迭代的值吗?不就是通过 context 指定 this 的值吗?我们可以直接这样写呐:

  1. _.map = function (obj, iteratee, context) {
  2. var length = obj.length, results = Array(length);
  3. for (var index = 0; index < length; index++) {
  4. results[index] = iteratee.call(context, obj[index], index, obj);
  5. }
  6. return results;
  7. };
  8.  
  9. // [2, 3, 4]
  10. console.log(_.map([1, 2, 3], function(item){
  11. return item + 1;
  12. }))
  13.  
  14. // [2, 3, 4]
  15. console.log(_.map([1, 2, 3], function(item){
  16. return item + this.value;
  17. }, {value: 1}))

你看看也没有什么问题呐,可是,万一 iteratee 我们不传入一个函数呢?比如我们什么也不传,或者传入一个对象,又或者传入一个字符串、数字呢?

如果用我们的方法自然是会报错的,那 underscore 呢?

  1. // 使用 underscore
  2.  
  3. // 什么也不传
  4. var result = _.map([1,2,3]); // [1, 2, 3]
  5.  
  6. // 传入一个对象
  7. var result = _.map([{name:'Kevin'}, {name: 'Daisy', age: 18}], {name: 'Daisy'}); // [false, true]
  8.  
  9. var result = _.map([{name: 'Kevin'}, {name: 'Daisy'}], 'name'); // ['Kevin', 'daisy']

我们会发现,underscore 竟然还能根据传入的值的类型不同,实现的效果不同。我们总结下:

  • 当 iteratee 不传时,返回一个相同的数组。
  • 当 iteratee 为一个函数,正常处理。
  • 当 iteratee 为一个对象,返回元素是否匹配指定的对象。
  • 当 iteratee 为字符串,返回元素对应的属性值的集合。
    由此,我们可以推测在 underscore 的 cb 函数中,有对 iteratee 值类型的判断,然后根据不同的类型,返回不同的 iteratee 函数。

cb

所以我们来看看 cb 函数的源码:

  1. var cb = function(value, context, argCount) {
  2.  
  3. if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
  4.  
  5. if (value == null) return _.identity;
  6.  
  7.  
  8. if (_.isObject(value) && !_.isArray(value)) return _.matcher(value);
  9.  
  10. return _.property(value);
  11. };

这一看就牵扯到了 8 个函数!不要害怕,我们一个一个看。

  1. if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
  1. _.iteratee = builtinIteratee = function(value, context) {
  2. return cb(value, context, Infinity);
  3. };

因为 的缘故, 值为 false,所以正常情况下 _.iteratee(value, context) 并不会执行。

但是如果我们在外部修改了 .iteratee 函数,结果便会为 true,cb 函数直接返回 .iteratee(value, context)

这个意思其实是说用我们自定义的 _.iteratee 函数来处理 value 和 context。

试想我们并不需要现在 _.map 这么强大的功能,我只希望当 value 是一个函数,就用该函数处理数组元素,如果不是函数,就直接返回当前元素,我们可以这样修改:

当然更多的情况是自定义对不同的 value 使用不同的处理函数,值得注意的是,underscore 中的多个函数都是用了 cb 函数,而因为 cb 函数使用了 _.iteratee 函数,如果你修改这个函数,其实会影响多个函数,这些函数基本都属于集合函数,具体包括 map、find、filter、reject、every、some、max、min、sortBy、groupBy、indexBy、countBy、sortedIndex、partition、和 unique。

_.identity

  1. if (value == null) return _.identity;

让我们看看 _.identity 的源码:

  1. _.identity = function(value) {
  2. return value;
  3. };

这也就是为什么当 map 的第二个参数什么都不传的时候,结果会是一个相同数组的原因。

  1. _.map([1,2,3]); // [1, 2, 3]

如果直接看这个函数,可能觉得没有什么用,但用在这里,却又十分的合适。

optimizeCb

  1. if (_.isFunction(value)) return optimizeCb(value, context, argCount);

当 value 是一个函数的时候,就传入 optimizeCb 函数,我们来看看 optimizeCb 函数:

  1. var optimizeCb = function(func, context, argCount) {
  2. // 如果没有传入 context,就返回 func 函数
  3. if (context === void 0) return func;
  4. switch (argCount) {
  5. case 1:
  6. return function(value) {
  7. return func.call(context, value);
  8. };
  9. case null:
  10. case 3:
  11. return function(value, index, collection) {
  12. return func.call(context, value, index, collection);
  13. };
  14. case 4:
  15. return function(accumulator, value, index, collection) {
  16. return func.call(context, accumulator, value, index, collection);
  17. };
  18. }
  19. return function() {
  20. return func.apply(context, arguments);
  21. };
  22. };

也许你会好奇,为什么我要对 argCount 进行判断呢?就不能直接返回吗?比如这样:

而为什么当参数是 3 个时候,参数名称分别是 value, index, collection ,又为什么没有参数为 2 的情况呢?其实这都是根据 underscore 函数用到的情况,没有函数用到两个参数,于是就省略了,像 map 函数就会用到 3 个参数,就根据这三个参数的名字起了这里的变量名啦。

  1. if (_.isObject(value) && !_.isArray(value)) return _.matcher(value);

这段就是用来处理当 map 的第二个参数是对象的情况:

  1. // 传入一个对象
  2. var result = _.map([{name:'Kevin'}, {name: 'Daisy', age: 18}], {name: 'Daisy'}); // [false, true]

如果 value 是一个对象,并且不是数组,就使用 _.matcher 函数。看看各个函数的源码:

  1. var nativeIsArray = Array.isArray;
  2.  
  3. _.isArray = nativeIsArray || function(obj) {
  4. return Object.prototype.toString.call(obj) === '[object Array]';
  5. };
  6. _.isObject = function(obj) {
  7. var type = typeof obj;
  8. return type === 'function' || type === 'object' && !!obj;
  9. };
  10.  
  11.  
  12. // extend 函数可以参考 《JavaScript 专题之手写一个 jQuery 的 extend》
  13. _.matcher = function(attrs) {
  14. attrs = _.extend({}, attrs);
  15. return function(obj) {
  16. return _.isMatch(obj, attrs);
  17. };
  18. };
  19.  
  20. // 该函数判断 attr 对象中的键值是否在 object 中有并且相等
  21.  
  22. // var stooge = {name: 'moe', age: 32};
  23. // _.isMatch(stooge, {age: 32}); => true
  24.  
  25. // 其中 _.keys 相当于 Object.keys
  26. _.isMatch = function(object, attrs) {
  27. var keys = _.keys(attrs), length = keys.length;
  28. if (object == null) return !length;
  29. var obj = Object(object);
  30. for (var i = 0; i < length; i++) {
  31. var key = keys[i];
  32. if (attrs[key] !== obj[key] || !(key in obj)) return false;
  33. }
  34. return true;
  35. };

_.property

  1. return _.property(value);

这个就是处理当 value 是基本类型的值的时候,返回元素对应的属性值的情况:

  1. var result = _.map([{name: 'Kevin'}, {name: 'Daisy'}], 'name'); // ['Kevin', 'daisy']

我们看下源码:

我们好像发现了新大陆,原来 value 还可以传一个数组,用来取深层次的值,举个例子:

  1. var person1 = {
  2. child: {
  3. nickName: 'Kevin'
  4. }
  5. }
  6.  
  7. var person2 = {
  8. child: {
  9. nickName: 'Daisy'
  10. }
  11. }
  12.  
  13. var result = _.map([person1, person2], ['child', 'nickName']);

最后

如果你想学习 underscore 的源码,在分析集合相关的函数时一定会接触 cb 和 optimizeCb 函数,先掌握这两个函数,会帮助你更好更快的解读源码。

underscore 系列目录地址:https://github.com/mqyqingfeng/Blog

underscore 系列预计写八篇左右,重点介绍 underscore 中的代码架构、链式调用、内部函数、模板引擎等内容,旨在帮助大家阅读源码,以及写出自己的 undercore。

如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎 star,对作者也是一种鼓励。