Underscore.js是一个很精干、实用库。它提供了一整套函数式编程的实用功能,但是没有扩展任何JavaScript内置对象,极大的方便了javaScript的编程。
第一部分
// 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.
//self 指窗口本身,它返回的对象跟window对象是一模一样的。也正因为如此,window对象的常用方法和函数都可以用self代替window
// Global
// 1)所有在全局作用域内定义的属性和方法,都是Global对象的属性。
// 2)Global对象不能直接使用,也不能用new运算符创建。
// 3)Global对象在JavaScript引擎被初始化时创建,并初始化其方法和属性。
// 4)浏览器把Global对象作为window对象的一部分实现了,因此,所有的全局属性和函数都是window对象的属性和方法。
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:
//prototype是函数的一个属性,并且是函数的原型对象。引用它的必然是函数
//原型对象,取别名,方别直接调用 Array无法直接使用push,例如Array.push 会报错
var ArrayProto = Array.prototype,
ObjProto = Object.prototype;
//ES6引入了一种新的原始数据类型Symbol,表示独一无二的值。它是JavaScript语言的第七种数据类型
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,
//Object的hasOwnProperty()方法返回一个布尔值,判断对象是否包含特定的自身(非继承)属性。
hasOwnProperty = ObjProto.hasOwnProperty;
// All ECMAScript 5 native function implementations that we hope to use
// are declared here.
//isArray() 方法用于判断一个对象是否为数组。如果对象是数组返回 true,否则返回 false。
var nativeIsArray = Array.isArray,
//Object.keys() 方法会返回一个由一个给定对象的自身可枚举属性组成的数组,数组中属性名的排列顺序和使用 for…in 循环遍历该对象时返回的顺序一致 。
nativeKeys = Object.keys,
//Object.create(proto [, propertiesObject ]) 是E5中提出的一种新的对象创建方式,第一个参数是要继承的原型,如果不是一个子函数,可以传一个null,第二个参数是对象的属性描述符,这个参数是可选的。
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) {
// ECMAScript 引入了另一个 Java 运算符 instanceof 来解决这个问题。instanceof 运算符与 typeof 运算符相似,
//用于识别正在处理的对象的类型。与 typeof 方法不同的是,instanceof 方法要求开发者明确地确认对象为某特定类型
if (obj instanceof _) return obj;
//函数_相当于一个构造函数
if (!(this instanceof _)) return new _(obj);
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) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.9.1';