- 1(function() {
- 2
- var root = this;
- 3 4 // 核心函数
- 5 // `_` 其实是一个构造函数
- 6
- var _ = function(obj) {
- 7 // 以下均针对 OOP 形式的调用
- 8 // 如果是非 OOP 形式的调用,不会进入该函数内部
- 9 // 如果 obj 已经是 `_` 函数的实例,则直接返回 obj
- 10
- if (obj instanceof _) return obj;
- 11 12 // 如果不是 `_` 函数的实例
- 13 // 则调用 new 运算符,返回实例化的对象
- 14
- if (! (this instanceof _)) return new _(obj);
- 15 16 // 将 obj 赋值给 this._wrapped 属性
- 17 this._wrapped = obj;
- 18
- };
- 19 20 // 将上面定义的 `_` 局部变量赋值给全局对象中的 `_` 属性
- 21 // 即客户端中 window._ = _
- 22 // 服务端(node)中 exports._ = _
- 23 // 同时在服务端向后兼容老的 require() API
- 24 // 这样暴露给全局后便可以在全局环境中使用 `_` 变量(方法)
- 25
- if (typeof exports !== 'undefined') {
- 26
- if (typeof module !== 'undefined' && module.exports) {
- 27 exports = module.exports = _;
- 28
- }
- 29 exports._ = _;
- 30
- } else {
- 31 root._ = _;
- 32
- }
- 33 34 // ..... 定义工具函数 如 _.each, _.map 等
- 35 36 37 _.mixin = function(obj) {
- 38 // 遍历 obj 的 key,将方法挂载到 Underscore 上
- 39 // 其实是将方法浅拷贝到 _.prototype 上
- 40 _.each(_.functions(obj), 41
- function(name) {
- 42 // 直接把方法挂载到 _[name] 上
- 43 // 调用类似 _.myFunc([1, 2, 3], ..)
- 44
- var func = _[name] = obj[name];
- 45 46 // 浅拷贝
- 47 // 将 name 方法挂载到 _ 对象的原型链上,使之能 OOP 调用
- 48 _.prototype[name] = function() {
- 49 // 第一个参数
- 50
- var args = [this._wrapped];
- 51 52 // arguments 为 name 方法需要的其他参数
- 53 push.apply(args, arguments);
- 54 // 执行 func 方法
- 55 // 支持链式操作
- 56
- return result(this, func.apply(_, args));
- 57
- };
- 58
- });
- 59
- };
- 60 61 // Add all of the Underscore functions to the wrapper object.
- 62 // 将前面定义的 underscore 方法添加给包装过的对象
- 63 // 即添加到 _.prototype 中
- 64 // 使 underscore 支持面向对象形式的调用
- 65 _.mixin(_);
- 66 67 // Add all mutator Array functions to the wrapper.
- 68 // 将 Array 原型链上有的方法都添加到 underscore 中
- 69 _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], 70
- function(name) {
- 71
- var method = ArrayProto[name];
- 72 _.prototype[name] = function() {
- 73
- var obj = this._wrapped;
- 74 method.apply(obj, arguments);
- 75 76
- if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
- 77 78 // 支持链式操作
- 79
- return result(this, obj);
- 80
- };
- 81
- });
- 82 83 // Add all accessor Array functions to the wrapper.
- 84 // 添加 concat、join、slice 等数组原生方法给 Underscore
- 85 _.each(['concat', 'join', 'slice'], 86
- function(name) {
- 87
- var method = ArrayProto[name];
- 88 _.prototype[name] = function() {
- 89
- return result(this, method.apply(this._wrapped, arguments));
- 90
- };
- 91
- });
- 92 // 一个包装过(OOP)并且链式调用的对象
- 93 // 用 value 方法获取结果
- 94 _.prototype.value = function() {
- 95
- return this._wrapped;
- 96
- };
- 97 98 _.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
- 99 100 _.prototype.toString = function() {
- 101
- return '' + this._wrapped;
- 102
- };
- 103 104
- }.call(this))
来源: http://www.cnblogs.com/lijiayi/p/sourcecode.html