admin管理员组文章数量:1434381
When exporting a module that has another dependency, is it best to include that dependency within the module export function or outside of it? I usually see the latter, but it seems like it would be best to keep it in the local scope.
For example:
var foo = require('foo');
module.exports = function(d) {
return foo(d)/2;
}
vs.
module.exports = function(d) {
var foo = require('foo');
return foo(d)/2;
}
When exporting a module that has another dependency, is it best to include that dependency within the module export function or outside of it? I usually see the latter, but it seems like it would be best to keep it in the local scope.
For example:
var foo = require('foo');
module.exports = function(d) {
return foo(d)/2;
}
vs.
module.exports = function(d) {
var foo = require('foo');
return foo(d)/2;
}
Share
Improve this question
asked Nov 19, 2014 at 4:32
jczaplewjczaplew
1,7511 gold badge18 silver badges22 bronze badges
1 Answer
Reset to default 7Only things exposed on module.exports
and global
can be accessed from other modules in node. Unlike in the browser, var
creates a local reference. To quote from node's documentation:
In browsers, the top-level scope is the global scope. That means that in browsers if you're in the global scope var something will define a global variable. In Node this is different. The top-level scope is not the global scope;
var something
inside a Node module will be local to that module.
The difference between the two versions is therefore minimal - the first incurs a lookup in the local scope, while the other hits require.cache
every time the function is invoked. From what I have seen of node code, the former (var someVar = require('something');
) seems to be preferred.
本文标签: javascriptScope of dependencies when exporting a module in NodejsStack Overflow
版权声明:本文标题:javascript - Scope of dependencies when exporting a module in Node.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745636394a2667584.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论