读白刃underscore疑惑分析--underscore源码学习一
来源:互联网 发布:c语言关键字及其含义 编辑:程序博客网 时间:2024/05/23 15:43
参考文章:http://www.cnblogs.com/WhiteBlade/p/5215434.html
underscore源码1.8.3
困惑一:nodeJs对于通用模块的封装
解析一:
通过判断exports是否存在来决定将局部变量 _ 赋值给exports,向后兼容旧的require() API,如果在浏览器中,通过一个字符串标识符“_”作为一个全局对象;完整的闭包:
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `exports` on the server.
var root = this;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
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 the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
}).call(this);
通过function定义构建了一个闭包,call(this)是将function在this对象下调用,以避免内部变量污染到全局作用域。浏览器中,this指向的是全局对象(window对象),将“_”变量赋在全局对象上“root._”,以供外部调用。
在封装Node.js和前端通用的模块时,可以使用以下逻辑:
if (typeof exports !== "undefined") {
exports.** = **;
} else {
this.** = **;
}
即,如果exports对象存在,则将局部变量装载在exports对象上,如果不存在,则装载在全局对象上。如果加上ADM规范的兼容性,那么多加一句判断:
if (typeof define === "function" && define.amd){}
谨以此文给自己解惑
- 读白刃underscore疑惑分析--underscore源码学习一
- 读白刃underscore疑惑分析--underscore源码学习二
- 读白刃underscore疑惑分析--underscore源码学习三
- Underscore.js源码分析(一)
- underscore.js源码分析
- 源码学习----underscore
- Underscore 源码学习笔记
- underscore源码学习(2)
- Underscore
- Underscore
- Underscore.js 1.3.3 源码分析收藏
- underScore 源码解析(一)----简单介绍
- underScore 源码解析(一)---- 结构
- V-1.8.2 underscore源码解析(一)
- underscore源码学习笔记(1)
- underScore源码解析-----Collections
- 阅读underscore源码笔记
- underscore源码经典--收藏
- C++编程经验总结3
- 线程问题
- tomcat启动时出现异常Exception loading sessions from persistent storage
- Qt-信号/槽(single/slot)机制
- 上班第四天
- 读白刃underscore疑惑分析--underscore源码学习一
- selectKey
- JSP数据交互
- Android四大组件之--Activity的深入浅出
- Tomcat部署时war和war exploded区别以及平时踩得坑
- 归纳、递归和归简-Python算法
- 关于PHP写APP接口的安全问题探讨
- stm32的程序下载方式ISP、JFLASH、MDK总结
- svn 添加用户名密码