js模块的实现
来源:互联网 发布:淘宝网打折耐克女鞋 编辑:程序博客网 时间:2024/05/18 09:08
node中模块的实现,其实是依赖于闭包的,也就是说,module,exports其实都是外部传入的参数,这个简化形式如下:
function NativeModule(id){ this.id=id; this.filename=id+".js"; this.exports={};}NativeModule.require=function(id){ var module=new NativeModule(id); module.compile(); return module.exports();};NativeModule.prototype.compile = function() { (function(exports, require, module, __filename, __dirname){ exports=module.exports=function(){alert("leexiaosi")}; }(this.exports, NativeModule.require, this, this.filename));};NativeModule.require("leexiaosi")
(附:上面的代码可以复制出来直接运行)
通过上面的代码我们惊奇的发现,其实我们看见的模块文件的代码,一般而言都是类似
exports=module.exports=function(){alert("leexiaosi")};
同时我们也就明白,为什么在模块文件中用var定义的变量都是私有的了。这里关键点就是
NativeModule.prototype.compile
这个函数的实现。为了方便理解,我们设
var fnImport=function(exports, require, module, __filename, __dirname)
那么,根据闭包的原理,这个函数在执行时,其[[scope]]会记录fnImport这个函数定义的作用域的各个变量,
- fnImport函数中的形参值,即this.exports, NativeModule.require, this, this.filename
- fnImport函数中function声明的函数
- fnImport函数中通过var声明的变量
- fnImport函数的父函数的作用域[[scope]]
fnImport这个函数对其fnImport.[[scope]]的操作都是有权限的。故this.exports会被更改,尽管在NativeModule的构造函数中this.exports的定义是空对象。
当然,事实上的NativeModule的实现要比这个复杂得多,尽管一般而言,非核心模块加载都是依赖于module这个模块,但是,module的实现模块加载的基本思想也是这样,只是module中增加了模块的检索功能。而模块文件中,require正是NativeModule.require这个函数。从return module.exports()来看,require初次加载模块时候必然是阻塞的(初次加载之后会被缓存,所以加载之后再require就不是阻塞的了)。
原文地址:http://cnodejs.org/blog/?p=997
- js模块的实现
- 用C/C++来实现 Node.js 的模块(上)
- 使用Node.js Net 模块实现简单的chat room
- 使用node.js的http模块实现爬虫小工具
- 使用readline模块如何实现Node.js的输入输出?
- 【Node.js基础篇】(九)使用readline模块实现Node.js的输入输出
- Qomolangma实现篇(一):内核载入模块system.js的实现
- Qomolangma实现篇(一):内核载入模块system.js的实现
- Js动态添加div实现模块复制
- Node.js:dgram模块实现UDP通信
- js 实现标题模块置顶显示
- js实现内容模块展开和收缩
- js实现简易模块加载器
- js模块开发(同步模块)实现原理
- Node.js的模块机制
- node.js的模块管理
- Node.js 的 http 模块
- Node.js的模块机制
- 三维凸包
- Action可以传值到js里
- ubuntu 安装OpenCV2.3
- cd的替代命令
- 函数对象(Function Objects-STL)
- js模块的实现
- 学习Python
- 一线网页游戏程序员日志 (一)
- QQ拼音输入法如何直接切换简繁体
- 等待队列一
- 高级软件开发工程师 | 流媒体服务器开发工程师
- Failed to connect to the specified server. Server library could not be loaded
- iOS 简单画板
- FAQ_17 android string.xml 里面的 %