(function() {

  // Baseline setup
// -------------- // Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
/*
判断root是window/global/this
*/
var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this; // Save the previous value of the `_` variable.
/*
保存全局下之前的'_'变量
若变量冲突,则可以利用此变量进行恢复
*/
var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version:
/*
原型赋值,以便压缩
*/
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null; // Create quick reference variables for speed access to core prototypes.
/*
将内置对象原型中的常用方法赋值给引用变量,以便更方便的引用
*/
var push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
/*
定义了一些ECMAScript 5方法
*/
var nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeCreate = Object.create; // Naked function reference for surrogate-prototype-swapping.
/*
定义一个裸函数
*/
var Ctor = function(){}; // Create a safe reference to the Underscore object for use below.
/*
创建'_'函数(对象)
*/
var _ = function(obj) {
/*
如果'_'的prototype在obj的原型链上,直接返回obj
*/
if (obj instanceof _) return obj;
/*
如果不在,new一个'_'对象
*/
if (!(this instanceof _)) return new _(obj);
/*
如果都不是,则将obj的引用放在_.wrapped属性中????????????????????????????????????????????????????????????????
*/
this._wrapped = obj;
}; // Export the Underscore object for **Node.js**, with
// backwards-compatibility for their old module API. If we're in
// the browser, add `_` as a global object.
// (`nodeType` is checked to ensure that `module`
// and `exports` are not HTML elements.)
/*
判断宿主
*/
if (typeof exports != 'undefined' && !exports.nodeType) {
if (typeof module != 'undefined' && !module.nodeType && module.exports) {//node
exports = module.exports = _;
}
exports._ = _;
} else {//浏览器,放在window的属性下
root._ = _;
} // Current version.
_.VERSION = '1.8.3'; // Internal function that returns an efficient (for current engines) version
// of the passed-in callback, to be repeatedly applied in other Underscore
// functions.
/*
用于内部使用的高阶函数,传入回调函数
主要用来执行函数并改变所执行函数的作用域,最后加了一个argCount参数来指定参数个数
*/
var optimizeCb = function(func, context, argCount) {
if (context === void 0) return func;
/*
对参数个数小于等于4的情况进行分类处理
*/
switch (argCount == null ? 3 : argCount) {
case 1: return function(value) {
return func.call(context, value);
};
// The 2-parameter case has been omitted only because no current consumers
// made use of it.
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);
};
}
/*
当argCount不为null或1/3/4时,直接调用func.apply(context, arguments)
*/
return function() {
return func.apply(context, arguments);
};
}; var builtinIteratee; // An internal function to generate callbacks that can be applied to each
// element in a collection, returning the desired result — either `identity`,
// an arbitrary callback, a property matcher, or a property accessor.
/*
判断参数类型
*/
var cb = function(value, context, argCount) {
if (_.iteratee !== builtinIteratee) return _.iteratee(value, context);
if (value == null) return _.identity;
if (_.isFunction(value)) return optimizeCb(value, context, argCount);// 参数是函数,返回optimizeCb函数的执行结果
if (_.isObject(value)) return _.matcher(value);// 参数是对象,则返回一个能判断对象是否相等的函数
return _.property(value);// 默认返回一个获取对象属性的函数
}; // External wrapper for our callback generator. Users may customize
// `_.iteratee` if they want additional predicate/iteratee shorthand styles.
// This abstraction hides the internal-only argCount argument.
_.iteratee = builtinIteratee = function(value, context) {
return cb(value, context, Infinity);
}; // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
/*
类似于es6中的rest param(function f(a, b, ...args) {})
把startIndex后面的参数放到一个数组里,并作为参数传给fn
*/
var restArgs = function(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;//'+'相当于Number()
return function() {
var length = Math.max(arguments.length - startIndex, 0),
rest = Array(length),
index = 0;
for (; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
case 2: return func.call(this, arguments[0], arguments[1], rest);
}
/*
将startIndex之前的参数放进数组中
*/
var args = Array(startIndex + 1);
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index];
}
args[startIndex] = rest;
return func.apply(this, args);
};
}; // An internal function for creating a new object that inherits from another.
/*
创建一个继承自另一个对象的新对象(原型继承)
*/
var baseCreate = function(prototype) {
if (!_.isObject(prototype)) return {};
if (nativeCreate) return nativeCreate(prototype);//如果存在Object.create,则直接使用
Ctor.prototype = prototype;
var result = new Ctor;
Ctor.prototype = null;
return result;
}; /*
获取对象及其原型链上的方法或属性
*/
var property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
}; // Helper for collection methods to determine whether a collection
// should be iterated as an array or as an object.
// Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
// Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
/*
判断类数组类型(有length属性,并且0 < length < MAX_ARRAY_INDEX)
*/
var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
var getLength = property('length');
var isArrayLike = function(collection) {
var length = getLength(collection);
return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX;
}; ...... }());

小结:

1.闭包

整个函数在一个闭包中,避免污染全局变量。通过传入this(其实就是window对象)来改变函数的作用域。和jquery的自执行函数其实是异曲同工之妙。这种传入全局变量的方式一方面有利于代码阅读,另一方面方便压缩。
underscore写法:

(function(){
...
}.call(this));

jquery写法:

(function(window, undefined) {
...
})(window);

2.格式

var
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind,
nativeCreate = Object.create;

3.高阶函数的使用

var property = function(key) {
return function(obj) {
return obj == null ? void 0 : obj[key];
};
};

参考资料:http://yalishizhude.github.io/2015/09/22/underscore-source/

underscore.js源码解析【'_'对象定义及内部函数】的更多相关文章

  1. underscore.js源码解析【对象】

    // Object Functions // ---------------- // Keys in IE < 9 that won't be iterated by `for key in . ...

  2. underscore.js源码解析(五)—— 完结篇

    最近公司各种上线,所以回家略感疲惫就懒得写了,这次我准备把剩下的所有方法全部分析完,可能篇幅过长...那么废话不多说让我们进入正题. 没看过前几篇的可以猛戳这里: underscore.js源码解析( ...

  3. underscore.js源码解析(四)

    没看过前几篇的可以猛戳这里: underscore.js源码解析(一) underscore.js源码解析(二) underscore.js源码解析(三) underscore.js源码GitHub地 ...

  4. underscore.js源码解析(三)

    最近工作比较忙,做不到每周两篇了,周末赶着写吧,上篇我针对一些方法进行了分析,今天继续. 没看过前两篇的可以猛戳这里: underscore.js源码解析(一) underscore.js源码解析(二 ...

  5. underscore.js源码解析(二)

    前几天我对underscore.js的整体结构做了分析,今天我将针对underscore封装的方法进行具体的分析,代码的一些解释都写在了注释里,那么废话不多说进入今天的正文. 没看过上一篇的可以猛戳这 ...

  6. underscore.js源码解析(一)

    一直想针对一个框架的源码好好的学习一下编程思想和技巧,提高一下自己的水平,但是看过一些框架的源码,都感觉看的莫名其妙,看不太懂,最后找到这个underscore.js由于这个比较简短,一千多行,而且读 ...

  7. underscore.js源码解析【函数】

    // Function (ahem) Functions // ------------------ // Determines whether to execute a function as a ...

  8. underscore.js源码解析【数组】

    // Array Functions // --------------- // Get the first element of an array. Passing **n** will retur ...

  9. underscore.js源码解析【集合】

    // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `f ...

随机推荐

  1. Moment.js 基本用法

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  2. django 模板使用

    1 配置 在工程中创建模板目录templates. 在settings.py配置文件中修改TEMPLATES配置项的DIRS值: TEMPLATES = [ { 'BACKEND': 'django. ...

  3. NPOI 导入为table 处理excel 格式问题

    ICell cell = row.GetCell(j); if (!cell.isDbNullOrNull()) { switch (cell.CellType) { case CellType.Bl ...

  4. etcd-v2第四集

    coreos把etcd的image放到自家的quay.io,而不是hub.docker,或许是竞争关系,但国内下载quay.io容器极难,反正shadowsocks是下载不了. 幸好有热心爱好者搬运到 ...

  5. HDU 3594.Cactus 仙人掌图

    Cactus Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Subm ...

  6. Linux 下编译 有多个子程序文件的Fortran程序

    第一种方法 ifort -o outprogram Source1.f90 Source2.f90 第二种 在主程序中include 'Source2.f90' program main call p ...

  7. SSM三大框架整合

    三大框架整合的思路 1.Dao层: Mybatis的配置文件:SqlMapConfig.xml 不需要配置任何内容,需要有文件头.文件必须存在. applicationContext-dao.xml: ...

  8. OpenCV+Qt+CMake安装+十种踩坑

    平台:win10 x64+opencv-3.4.1 + qt-x86-5.9.0 + cmake3.13.4 x64 OpenCV+Qt+CMake安装,及目前安装完后打包:mingw32-make时 ...

  9. web集成高德地图

    1.使用高德地图API需到官网添加一个Key,http://lbs.amap.com/dev/key/app 2.页面头引入 <div id="addressMap"> ...

  10. 包含复杂函数的excel 并下载

    POI 版本: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</a ...