NodeJS模块vs类 [英] NodeJS modules vs classes

查看:379
本文介绍了NodeJS模块vs类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,类与NodeJS(CommonJS)模块非常相似。你可以有很多,他们可以重复使用,他们可以互相使用,他们通常是一个一个文件。

To me classes are quite similar to NodeJS (CommonJS) modules. You can have many of them, they can be reused, they can use each other and they are generally one-per-file.

什么使模块与类不同?你使用它们的方式不同,命名空间的区别很明显。

What makes modules so different from classes? The way you use them differs, and the namespace difference is obvious. Besides that they seem very much the same thing to me or perhaps I am just not seeing the obvious benefit here.

推荐答案

模块是可以使用的模块,它们是非常相似的东西,更像包(使用Java术语)比类。您不实例化模块;只有一个副本。它是一个用于组织相关功能的工具,但它通常不封装对象的特定实例的数据。

Modules are more like packages (to use the Java term) than classes. You don't instantiate a module; there is only one copy of it. It's a tool for organizing related functionality, but it doesn't typically encapsulate the data of a particular instance of an object.

可能是类的最接近的模拟那些实际上在JavaScript中构造基于类的继承的库)只是一个构造函数。你当然可以把这些函数放在一个模块中。

Probably the closest analogue to a class (setting aside those libraries that actually construct class-based inheritance in JavaScript) is just a constructor function. You can of course put such functions inside a module.

function Car() {
    this.colour = 'red';
}
Car.prototype.getColour = function() { return this.colour; };

var myCar = new Car();
myCar.getColour(); // returns 'red'

你使用模块和类来封装,是不同的。

You use both modules and classes for encapsulation, but the nature of that encapsulation is different.

这篇关于NodeJS模块vs类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆