在nodejs中使用匿名函数

Siv*_*der 3 javascript node.js

编写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;


}());
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello World
[ReferenceError: a is not defined]
[ReferenceError: b is not defined]
Run Code Online (Sandbox Code Playgroud)

没有匿名函数的示例

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;
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Hello World
[ReferenceError: a is not defined]
[ReferenceError: b is not defined]
Run Code Online (Sandbox Code Playgroud)

Tha*_*you 8

你绝对不需要匿名功能

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;
Run Code Online (Sandbox Code Playgroud)

  • @naomik无论你个人如何看待它,隐藏信息都不符合StackOverflow的精神.解释为什么人们不应该使用它.信息每次都胜过无知. (2认同)