理解node中的require和exports

js模块的实现

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(this.id)};
       }
       (this.exports, NativeModule.require, this, this.filename)
   );
   //第二种自执行函数
    //(
    //      function(exports, require, module, filename, dirname)
    //      {
    //         exports=module.exports=function(){alert(this.id)};
    //    }
    // )(this.exports, NativeModule.require, this, this.filename)

};
NativeModule.require("我是id")

(附:上面的代码可以复制出来直接在控制台运行)

通过上面的代码我们惊奇的发现,其实我们看见的模块文件的代码,一般而言都是类似
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就不是阻塞的了
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值