将库声明为常量
在NodeJS世界中,我们需要使用require
函数的模块:
var foo = require ("foo");
在JavaScript中(也在NodeJS中),我们有const
关键字创build一个常量:
const
创build一个常量,该常量可以是声明它的函数的全局或局部的。 常量遵循与variables相同的范围规则。
例:
$ 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
时有什么不好/很好的效果,当需要库?
NodeJS对于需要const的库没有任何优化 – require
是一个简单的非本地函数,对于被赋值的variables的types,什么都不知道。 有需求的源代码:
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(如果你想得到真正的const对象使用Object.freeze(someObject)
)。
为了得出结论:效果与常见variables相同。 链接到NodeJS中使用的V8variables声明函数
事实certificate,对于依赖关系,使用const
over var
是一种常见的做法。 至less在Node.js源代码中,这是正在发生的事情:
-
http.js
所以,我猜这是一个很好的做法。 我也开始在模块中使用它。