Node.js 命名空间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9101028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:06:52  来源:igfitidea点击:

Node.js namespacing

node.js

提问by hacklikecrack

Struggling a little to make best use of Node's module/require()/exports set up to do proper OO programming. Is it good practice to create global namespace and not use exports (as in client side js app development)? So, in module (Namespace.Constructor.js):

努力充分利用 Node 的模块/require()/exports 设置来进行适当的 OO 编程。创建全局命名空间而不使用导出(如在客户端 js 应用程序开发中)是一种好习惯吗?因此,在模块 (Namespace.Constructor.js) 中:

Namespace = Namespace || {};
Namespace.Constructor = function () {
    //initialise
}
Namespace.Constructor.prototype.publicMethod = function () {
    // blah blah
}

... and in calling file just use...

...在调用文件时只需使用...

requires('Namespace.Constructor');
var object = new Namespace.Constructor();
object.publicMethod();

Thanks

谢谢

回答by Jon Nichols

In node.js, the module location is the namespace, so there's no need to namespace in the code as you've described. I think there are some issues with this, but they are manageable. Node will only expose the code and data that you attach to the module.exports object.

在 node.js 中,模块位置是命名空间,因此不需要像您描述的那样在代码中使用命名空间。我认为这有一些问题,但它们是可以管理的。Node 只会公开您附加到 module.exports 对象的代码和数据。

In your example, use the following:

在您的示例中,请使用以下内容:

var Constructor = function() {
  // initialize
}
Constructor.prototype.publicMethod = function() {}
module.exports = Constructor;

And then, in your calling code:

然后,在您的调用代码中:

var Constructor = require('./path/to/constructor.js');
var object = new Constructor();
object.publicMethod();