簡體   English   中英

如何導出在 node.js 命名空間中實現的類

[英]How To Export A Class Implemented In A Namespace In node.js

我在 node.js 4.5.0 的命名空間中創建了一個類,其實現如下;

//
// 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 中實例化和填充整數列表時,列表中的函數按預期工作。 例如;

//
// 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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM