nodejs中匿名函数的使用
Use of anonymous functions in nodejs
在编写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;
相关文章:
- nodejs中匿名函数的使用
- Nodejs模块函数返回未定义的,而不是异步的
- 在NodeJS中使用类函数作为事件侦听器
- NodeJS:函数与匿名函数
- 从多线程C++插件回调NodeJS Javascript函数
- 从Nodejs中的函数返回数组,并将其发送到ejs视图
- NodeJS:创建一个hash并返回一个函数的值
- TypeError:回调不是nodeJS中具有asyncJS的函数
- 更好的写法 NodeJS 读/写文件的函数
- 具有默认参数值的 ES6 类构造函数上的 NodeJS 错误
- 在特定时刻调用 NodeJs 函数
- Nodejs 异步任务和匿名函数
- 如何获取以编程方式定义nodejs函数的位置
- 导出对象与函数 NodeJs
- TypeError: http.listen 不是一个函数: NodeJS.
- 如何在自己的函数中定义回调函数?NodeJS
- 当移动到函数(nodejs, express)时,请求和响应对象变得未定义
- 将回调中的变量返回到已定义的函数NodeJS中
- 设置回调函数 nodejs 的值
- 查找调用函数(nodejs)的文件的位置