在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
是否有任何不良影响?
答案 0 :(得分:1)
答案 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变量声明函数