如何导出在名称空间中实现的类在node.js中

我在node.js 4.5.0的命名空间里创build了一个类,其实现如下:

// // Contents of MyList.js // "use strict"; var MyCollections {}; (function() { this.List = function () { // // Simple List implementation ... // } }).apply(MyCollections); 

在我想要实例化MyCollections.List类的脚本中,我编写了以下代码;

 // // Contents of CheckList.js // "using strict"; var collections = require('../MyList'); var list = new collections.List(); 

当通过节点运行上面的脚本时,我收到以下内容;

 PS C:\work\node.js\MyCollections\List> node .\CheckList.js Number of Items in List: 2 C:\work\node.js\MyCollections\List\CheckList.js:6 var list = new collections.List(); ^ TypeError: collections.List is not a function at Object.<anonymous> (C:\work\node.js\MyCollections\List\CheckList.js:6:12) at Module._compile (module.js:409:26) at Object.Module._extensions..js (module.js:416:10) at Module.load (module.js:343:32) at Function.Module._load (module.js:300:12) at Function.Module.runMain (module.js:441:10) at startup (node.js:139:18) at node.js:974:3 

鉴于上面的MyList.js中的List类的实现,我应该改变什么来使List类可导出,以便我可以在多个脚本中重用它?

我很抱歉,如果这是之前已经发布和回答,因为我可能已经用错误的术语来描述我正在尝试做什么。 我的意图是声明一个名称空间,并公开实现集合类的函数原型,在这种情况下是一个简单的列表,同时保持一定程度的封装。 我相信我的List类实现是正确的,因为当我试图实例化和填充列表中的整数在同一个脚本,MyList.js,列表中的function按预期工作。 例如;

 // // Statements after (function() { //... }).apply(MyCollections); // var list = new MyCollections.List(); list.append(1); list.append(2); list.append(3); list.append(4); console.log("Number of Items in List: " + list.count()); while (list.hasNext()) { var trace = 'Item ' + (list.position() + 1) + ' of ' + list.count() + ' = ' + list.getItem(); console.log(trace); list.next(); } // // Output: // Number of Items in List: 4 Item 1 of 4 = 1 Item 2 of 4 = 2 Item 3 of 4 = 3 Item 4 of 4 = 4 

提前感谢您的时间,帮助和耐心。

您需要导出MyCollections 。 将以下内容添加到您的MyList.js

 module.exports = MyCollections; 

所以更新的文件有以下内容:

 // // Contents of MyList.js // "use strict"; var MyCollections = {}; (function() { this.List = function () { // // Simple List implementation ... // } }).apply(MyCollections); module.exports = MyCollections;