一直想针对一个框架的源码好好的学习一下编程思想和技巧,提高一下自己的水平,但是看过一些框架的源码,都感觉看的莫名其妙,看不太懂,最后找到这个underscore.js由于这个比较简短,一千多行,而且读起来容易一些,所以就决定是它了,那废话不多说开始我们的源码学习。

underscore.js源码GitHub地址: https://github.com/jashkenas/underscore/blob/master/underscore.js
 
本文解析的underscore.js版本是1.8.3
 

结构解析

 
我们先从整体的结构开始分析(其中加入了注释加以解释说明)
 
 (function() {
// 创建一个root对象,在浏览器中表示为window(self)对象,在Node.js中表示global对象,
// 之所以用用self代替window是为了支持Web Worker
var root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global ||
this;
// 保存"_"(下划线变量)被覆盖之前的值
var previousUnderscore = root._;
// 原型赋值,便于压缩
var ArrayProto = Array.prototype, ObjProto = Object.prototype;
// 将内置对象原型中的常用方法赋值给引用变量,以便更方便的引用
var push = ArrayProto.push,
slice = ArrayProto.slice,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// 定义了一些ECMAScript 5方法
var nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeCreate = Object.create;
//跟神马裸函数有关,我也不清楚什么意思,有知道可以告诉我
var Ctor = function(){};
// 创建一个下划线对象
var _ = function(obj) {
// 如果在"_"的原型链上(即_的prototype所指向的对象是否跟obj是同一个对象,要满足"==="的关系)
if (obj instanceof _) return obj;
// 如果不是,则构造一个
if (!(this instanceof _)) return new _(obj);
// 将underscore对象存放在_.wrapped属性中
this._wrapped = obj;
};
// 针对不同的宿主环境, 将Undersocre的命名变量存放到不同的对象中
if (typeof exports != 'undefined' && !exports.nodeType) {//Node.js
if (typeof module != 'undefined' && !module.nodeType && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {//浏览器
root._ = _;
}
//版本号
_.VERSION = '1.8.3';
//下面是各种方法以后的文章中会具体说明
.
.
.
.
.
.
// 创建一个chain函数,用来支持链式调用
_.chain = function(obj) {
var instance = _(obj);
//是否使用链式操作
instance._chain = true;
return instance;
};
// 返回_.chain里是否调用的结果, 如果为true, 则返回一个被包装的Underscore对象, 否则返回对象本身
var chainResult = function(instance, obj) {
return instance._chain ? _(obj).chain() : obj;
};
// 用于扩展underscore自身的接口函数
_.mixin = function(obj) {
//通过循环遍历对象来浅拷贝对象属性
_.each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return chainResult(this, func.apply(_, args));
};
});
};
_.mixin(_);
// 将Array.prototype中的相关方法添加到Underscore对象中, 这样Underscore对象也可以直接调用Array.prototype中的方法
_.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
//方法引用
var method = ArrayProto[name];
_.prototype[name] = function() {
// 赋给obj引用变量方便调用
var obj = this._wrapped;
// 调用Array对应的方法
method.apply(obj, arguments);
if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];
//支持链式操作
return chainResult(this, obj);
};
}); // 同上,并且支持链式操作
_.each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
//返回Array对象或者封装后的Array
return chainResult(this, method.apply(this._wrapped, arguments));
};
});
//返回存放在_wrapped属性中的underscore对象
_.prototype.value = function() {
return this._wrapped;
}; // 提供一些方法方便其他情况使用
_.prototype.valueOf = _.prototype.toJSON = _.prototype.value;
_.prototype.toString = function() {
return '' + this._wrapped;
}; // 对AMD支持的一些处理
if (typeof define == 'function' && define.amd) {
define('underscore', [], function() {
return _;
});
}
}());

总结

具体分析在上面源码中的注释里写的已经很详细了,下面再从头理顺一下整体的结构:
 
首先underscore包裹在一个匿名自执行的函数当中
内部定义了一个"_"变量
将underscore中的相关方法添加到_原型中,创建的_对象就具备了underscore方法
将Array.prototype中的相关方法添加到Underscore对象中, 这样Underscore对象也可以直接调用Array.prototype中的方法

之后的文章中,我会针对underscore中的方法进行具体解析,感谢大家的观看,也希望能够和大家互相交流学习,有什么分析的不对的地方欢迎大家批评指出

underscore.js源码解析(一)的更多相关文章

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

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

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

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

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

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

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

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

  5. underscore.js源码解析【'_'对象定义及内部函数】

    (function() { // Baseline setup // -------------- // Establish the root object, `window` (`self`) in ...

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

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

  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. VS创建工程出错解决方案

    今天在用VS2010创建工程时出现错误:“ 此模板尝试加载组件程序集 “NuGet.VisualStudio.Interop, Version=1.0.0.0, Culture=neutral, Pu ...

  2. beta冲刺————第二天(2/5)

    完善具体内容: 前端: (1)添加了更多设置 (2)点击后出现底栏,分别可以进行字体背景设置.收藏.分享等操作,同时可以看出对文章的排版进行了完善 后端: 对阿里云服务器中的环境进行配置,同时熟悉阿里 ...

  3. [python] 在 python2和3中关于类继承的 super方法简要说明

    下面举一个例子,同样的代码使用 python2 和 python3 写的,大家注意两段程序中红色加粗的部分: python2的类继承使用super方法: #-*- coding:utf-8 -*- ' ...

  4. http-server

    http-server是基于node.js的一个简单.零配置的命令行web服务器,可以方便实现跨域资源请求, #全局安装: npm install http-server -g: 全局安装后就可以通过 ...

  5. 设置webstorm支持ES6语法

    1.  点击File目录下的Default Settings 2.  再依次点击Languages & Frameworks  ----->  JaveScript  ----> ...

  6. 禁止选择DIV内的文本(css,js写法)

    css:<span style="font-family:SimSun;font-size:18px;">/* 禁止选择div内的文字 */ #hall_body { ...

  7. 3.HBase In Action 第一章-HBase简介(1.1.1 大数据你好呀)

    Let's take a closer look at the term Big Data. To be honest, it's become something of a loaded term, ...

  8. 【转】如何打开注册表编辑器中存储用户信息的SAM文件?

    sam文件怎么打开 (Security Accounts Manager安全帐户管理器)负责SAM数据库的控制和维护.SAM数据库位于注册表HKLM\SAM\SAM下,受到ACL保护,可以使用rege ...

  9. shiro实战系列(十一)之Caching

    Shiro 开发团队明白在许多应用程序中性能是至关重要的.Caching 是从第一天开始第一个建立在 Shiro 中的一流功 能,以确保安全操作保持尽可能的快.   然而,Caching 作为一个概念 ...

  10. IO多路复用select/poll/epoll详解以及在Python中的应用

    IO multiplexing(IO多路复用) IO多路复用,有些地方称之为event driven IO(事件驱动IO). 它的好处在于单个进程可以处理多个网络IO请求.select/epoll这两 ...