是否需要将node.js模块包装在模块模式中? [英] Are node.js modules need to be wrapped inside the module pattern?

查看:70
本文介绍了是否需要将node.js模块包装在模块模式中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了确保适当的隔离,我倾向于将我编写的每个node.js模块包装在一个函数范围内:

To ensure proper isolation, I tend to wrap each node.js module that I write inside a function scope:

(function() {
  var express = require('express');
  var jade = require('jade');
  var moment = require('moment');

  exports.someFunction = function() {
    // do something    
  };

  exports.otherFunction = function() {
    // do something else
  };
})();

我已经做了一段时间了,但是我感觉到node.js的模块系统实际上正在为我做这件事,或者(换句话说)上面的代码等同于下面的代码:

I've been doing this for some time now, but I have the feeling that node.js' module system is actually doing this for me, or (in other words) that the above code is equivalent to the following code:

var express = require('express');
var jade = require('jade');
var moment = require('moment');

exports.someFunction = function() {
  // do something    
};
exports.otherFunction = function() {
  // do something else
};

这两个真的相等吗? 特别是,我想知道隔离级别是否相同:expressjademoment变量是否在模块本地? (即,我想确保它们未在全局范围内定义或干扰了此模块之外的任何其他定义.)

Are the two really equivalent? In particular, I am interested to know whether is the isolation level is the same: are the express, jade or moment variables local to the module? (i.e., I'd like to make sure that they are not defined in the global scope or interfere with any other definition outside of this module).

推荐答案

在模块中声明的变量是该模块的本地变量.可以安全地省略封闭功能.

Variables declared within a module are local to that module. It is safe to omit your enclosing function.

Node.js文档:

模块本地的变量将是私有的,就像模块包装在函数中一样

Variables local to the module will be private, as though the module was wrapped in a function

这篇关于是否需要将node.js模块包装在模块模式中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆