将库声明为常量

时间:2014-05-01 18:23:31

标签: javascript node.js variables constants

在NodeJS世界中,我们需要使用require函数的模块:

var foo = require ("foo");

在JavaScript(也在NodeJS中)中,我们使用const关键字创建一个常量:

  

const

     

创建一个常量,该常量可以是声明它的函数的全局或局部。常量遵循与变量相同的范围规则。

示例:

$ node
> const a = 10
undefined
> a
10
> a = 7
7
> a
10

我的问题是:要求库作为常量会好吗?

示例:

const foo = require ("foo")
    , http = require ("http")
    ;

/* do something with foo and http */

在需要库时,使用const代替var是否有任何不良影响?

2 个答案:

答案 0 :(得分:1)

事实证明,对const使用var进行依赖是一种常见做法。至少在Node.js源代码中会发生这种情况:

所以,我认为这是一个很好的做法。我也开始在my modules中使用它。

答案 1 :(得分:0)

NodeJS对要求为const的库没有任何优化 - require是一个简单的非本机函数,对于所分配的变量的类型一无所知。源代码为require

Module.prototype.require = function(path) {
  assert(util.isString(path), 'path must be a string');
  assert(path, 'missing path');
  return Module._load(path, this);
};

Module._load = function(request, parent, isMain) {
  if (parent) {
    debug('Module._load REQUEST  ' + (request) + ' parent: ' + parent.id);
  }

  var filename = Module._resolveFilename(request, parent);

  var cachedModule = Module._cache[filename];
  if (cachedModule) {
    return cachedModule.exports;
  }

  if (NativeModule.exists(filename)) {
    // REPL is a special case, because it needs the real require.
    if (filename == 'repl') {
      var replModule = new Module('repl');
      replModule._compile(NativeModule.getSource('repl'), 'repl.js');
      NativeModule._cache.repl = replModule;
      return replModule.exports;
    }

    debug('load native module ' + request);
    return NativeModule.require(filename);
  }

  var module = new Module(filename, parent);

  if (isMain) {
    process.mainModule = module;
    module.id = '.';
  }

  Module._cache[filename] = module;

  var hadException = true;

  try {
    module.load(filename);
    hadException = false;
  } finally {
    if (hadException) {
      delete Module._cache[filename];
    }
  }

  return module.exports;
};

更多时间库是一个对象(我认为你没有这样的库module.exports = 10)。

如果将对象声明为const,则可以更改对象的所有字段(如果要使用Object.freeze(someObject)得到realy const对象)。

结论:效果与公共变量相同。 NodeJS中使用的Link到V8变量声明函数