模块封装器


【The module wrapper】

在模块的代码执行之前,Node.js 会用一个函数封装器来封装它,形式如下:

【Before a module's code is executed, Node.js will wrap it with a function wrapper that looks like the following:】

(function(exports, require, module, __filename, __dirname) {
// Module code actually lives in here
}); 

通过这样做,Node.js 实现了以下几点:

【By doing this, Node.js achieves a few things:】

  • 它将顶层变量(用 varconstlet 定义的)限定在模块作用域内,而不是全局对象。
  • 它有助于提供一些看似全局的变量,但实际上是特定于模块的,例如:
    • 实现者可以使用的 moduleexports 对象,用于从模块中导出值。
    • 便捷变量 __filename__dirname,包含模块的绝对文件名和目录路径。