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

原创粉丝点击