源码分析/Underscore源码解析
< 源码分析
跳到导航
跳到搜索
一直想写一篇这样的文章,于是心动不如行动,这里选择的是 Underscore.js 1.8.3 版本,源码注释加在一起1625行。 ¶ Underscore.js 1.8.3 http://underscorejs.org (c) 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors Underscore may be freely distributed under the MIT license. ¶ 这里我们首先看到的是一个闭包,概念不再熬述,诸君有意详勘闭包的概念,请移步 Closures。源码如下: (function() { ¶ 这里如果这里有 this 那么一定是指向 window,即: ¶ Window {external: Object, chrome: Object, document: document, speechSynthesis: SpeechSynthesis, caches: CacheStorage…} ¶ window 具有的众多属性中就包含了 self 引用其自身,根据javascript的运算符执行顺序 Expressions and operators: ¶ . [] () 字段访问、数组下标、函数调用以及表达式分组 ++ -- - ~ ! delete new typeof void 一元运算符、返回数据类型、对象创建、未定义值 * / % 乘法、除法、取模 + - + 加法、减法、字符串连接 << >> >>> 移位 < <= > >= instanceof 小于、小于等于、大于、大于等于、instanceof == != === !== 等于、不等于、严格相等、非严格相等 & 按位与 ^ 按位异或 | 按位或 && 逻辑与 || 逻辑或 ?: 条件 = 赋值、运算赋值 , 多重求值 ¶ 这里首先判断的是存在 self 或者 node 环境下的全局变量 global,然后复制给 root,作为根对象。
var root = typeof self == 'object' && self.self === self && self || typeof global == 'object'
&& global.global === global && global || this;