在编写nodejs模块时是否有用于匿名函数的功能。我知道我们使用匿名函数来限制用于特定模块的变量/函数的范围。但是,在nodejs中,我们使用modules.exports在模块外部创建了一个函数或变量,因此不应该使用匿名函数?在nodejs中使用匿名函数
我问这个问题的原因是因为流行的节点模块(如async.js)广泛使用匿名函数。
实施例与匿名功能
1)test_module.js
(function(){
var test_module = {};
var a = "Hello";
var b = "World";
test_module.hello_world = function(){
console.log(a + " " + b);
};
module.exports = test_module;
}());
2)test.js
var test_module = require("./test_module");
test_module.hello_world();
try {
console.log("var a is " + a + "in this scope");
}
catch (err){
console.log(err);
}
try {
console.log("var a is " + b + "in this scope");
}
catch (err){
console.log(err);
}
输出:
Hello World
[ReferenceError: a is not defined]
[ReferenceError: b is not defined]
实施例而不匿名功能
1)test_module2.js
var test_module = {};
var a = "Hello";
var b = "World";
test_module.hello_world = function(){
console.log(a + " " + b);
};
module.exports = test_module;
2)test2.js
var test_module = require("./test_module2");
test_module.hello_world();
try {
console.log("var a is " + a + "in this scope");
}
catch (err){
console.log(err);
}
try {
console.log("var a is " + b + "in this scope");
}
catch (err){
console.log(err);
}
输出:
Hello World
[ReferenceError: a is not defined]
[ReferenceError: b is not defined]
节点。js模块提供了自己的封装。所以不需要用这种方式来包装'module.exports'。如果你有嵌套类,你可能需要它。但是这个事实本身实际上会暗示将这个嵌套类包装到另一个模块中...... –