nodejs中匿名函数的使用

Use of anonymous functions in nodejs

本文关键字:函数 nodejs      更新时间:2023-09-26

在编写nodejs模块时是否使用匿名函数。我知道我们使用匿名函数来限制用于特定模块的变量/函数的范围。然而,在nodejs中,我们使用modules.exports使函数或变量在模块外可用,因此匿名函数难道不是不必要的吗?

我之所以这么问,是因为流行的节点模块(如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]

您绝对不需要匿名函数

Node保证您有一个干净的"命名空间"来处理每个文件

每个文件/模块中唯一"可见"的内容是您使用module.exports 显式导出的内容


您的test_module2.js更受欢迎,尽管我仍会做一些更改。最值得注意的是,您不必将myModule定义为文件中的对象。您可以将该文件视为一个模块。

test_module3.js

var a = "Hello";
var b = "World";
function helloWorld() {
  console.log(a, b);
}
exports.helloWorld = helloWorld;