Node js:定义实体类的最佳方式

Ram*_*mar 5 entity-framework node.js

我正在用 Node.js 编写一个工具。我想在node js中定义一些POJO。我对 Node.js 没有太多经验。我来自 JAVA 背景,其中类用于定义实体。我现在定义实体的一种方式是:-

function Person(name) {
    this.name = name;
    this.values = [];
    this.characteristics = {};
}
Run Code Online (Sandbox Code Playgroud)

但这是在一个 JS 文件中定义的。为了使其在其他 JS 文件中可用,我必须导出此函数。这是定义实体的最佳方法还是有其他方法可以定义类格式的东西?

Vto*_*one 3

这对于创建对象来说就很好了。如果您开始使用像 mongo 这样的数据库,您可能最好使用 mongoose 创建对象,但这也是个人喜好。至于你的例子 -

1) 出口人

module.exports = Person;
Run Code Online (Sandbox Code Playgroud)

2)从另一个文件导入Person

const Person = require('../path/to/Person');
Run Code Online (Sandbox Code Playgroud)

3)创建Person,使用new关键字调用构造函数(非常重要)

const mitch = new Person('Mitch');
Run Code Online (Sandbox Code Playgroud)

你应该阅读javascript's prototype. 每个对象都有一个对 的引用Object.prototype。然后,您可以使用 创建对象 来Object.create(obj)创建对象并将新对象的原型分配为传递给的引用Object.create(obj)

这是来自 MDN 的示例

// Shape - superclass
function Shape() {
  this.x = 0;
  this.y = 0;
}

// superclass method
Shape.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
  console.info('Shape moved.');
};

// Rectangle - subclass
function Rectangle() {
  Shape.call(this); // call super constructor.
}

// subclass extends superclass
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.constructor = Rectangle;

var rect = new Rectangle();

console.log('Is rect an instance of Rectangle?',
  rect instanceof Rectangle); // true
console.log('Is rect an instance of Shape?',
  rect instanceof Shape); // true
rect.move(1, 1); // Outputs, 'Shape moved.'
Run Code Online (Sandbox Code Playgroud)