2015-04-07 155 views
3

在编写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] 
+4

节点。js模块提供了自己的封装。所以不需要用这种方式来包装'module.exports'。如果你有嵌套类,你可能需要它。但是这个事实本身实际上会暗示将这个嵌套类包装到另一个模块中...... –

回答

8

你绝对不需要匿名函数

节点,保证你一个干净的 “命名空间”与每个文件一起工作

从每个文件/模块的唯一的东西“看得见”是你明确出口使用module.exports


东西你test_module2.js,但最好不过我还是会做一些修改。最值得注意的是,您不必将myModule定义为文件中的对象。您可以将该文件视为模块。

test_module3.js

var a = "Hello"; 
var b = "World"; 

function helloWorld() { 
    console.log(a, b); 
} 

exports.helloWorld = helloWorld; 
+1

以及作为'global'对象的属性指定的任何对象。 – Matt

+0

@MS_SL我礼貌地要求你删除你的评论。不要在node.js中向我提及'global'。在我的答案中,我甚至不希望对其使用的建议有所暗示。老实说,我宁愿人们甚至不知道它存在于node.js中。 – naomik

+1

谢谢你的回答。我很好奇,因为我使用的是使用匿名函数的流行节点模块。现在我明白了原因是因为该模块可以用于节点和前端JS(包括使用脚本标记)。 – SivaDotRender

-1

从我的使用中发展的NodeJS web应用程序没有什么经验,但绝对没有必要出口匿名函数!

+0

这不提供问题的答案。要批评或要求作者澄清,在他们的帖子下留下评论 - 你总是可以评论你自己的帖子,一旦你有足够的[声誉](http://stackoverflow.com/help/whats-reputation),你会能够[评论任何帖子](http://stackoverflow.com/help/privileges/comment)。 – KeatsPeeks

+0

@SivaDotRender我明白了 –