上一篇文章中使用了map函数作为例子介绍了underscore是怎么实现链式调用的。
这里具体讲讲map内部结构。
_.map = function(obj, iteratee, context) {
//生成不同功能迭代器
var iteratee = cb(iteratee, context);
//分辨 obj是数组对象, 还是object对象
var keys = !_.isArray(obj) && Object.keys(obj);
var length = (keys || obj).length;
var result = Array(length);//生成新的数组
for (var index = 0; index < length; index++) {
var currentKey = keys ? keys[index] : index;
result[index] = iteratee(obj[currentKey], index, obj);
}
return result;//返回新的数组
}
函数中调用cb函数:
var cb = function(iteratee, context, count) {
if (iteratee == null) {
return _.identity;
}
if (_.isFunction(iteratee)) {
return optimizeCb(iteratee, context, count);
}
}
//cb的作用:判断iteratee是否存在:
_.identity = function(value) {//不存在则使用默认迭代器
return value;
}
//以及是否是函数:是就调用optimizeCb函数:
//optimizeCb优化迭代器 //这个我觉得是为了optimizeCb复用。
var optimizeCb = function(func, context, count) {
if (context == void 0) {// void 0为undefined
return func;
}
switch (count == null ? 3 : count) {
case 1:
return function(value) {
return func.call(context, value);
};
case 3:
return function(value, index, obj) {
return func.call(context, value, index, obj);
};
}
}