【问题标题】:How To Export A Class Implemented In A Namespace In node.js如何在 node.js 中导出在命名空间中实现的类
【发布时间】:2017-01-18 20:55:27
【问题描述】:

我在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

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

【问题讨论】:

    标签: javascript node.js class namespaces export


    【解决方案1】:

    您需要导出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;
    

    【讨论】:

    • 感谢您的快速回复;你的答案很准确:“使用严格”; var collections = require('./List'); var list = new collections.List();
    • @ClockEndGooner (thumbsup)
    猜你喜欢
    • 2021-02-26
    • 2016-03-02
    • 2013-08-21
    • 2012-02-05
    • 2020-07-25
    • 2013-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多