节点js:定义实体类的最好方法

我在节点js写一个工具。 我想在节点js中定义一些POJO。 我在Node js上没有太多的经验。 我来自JAVA背景,类用于定义实体。 我现在定义实体的一种方法是:

function Person(name) { this.name = name; this.values = []; this.characteristics = {}; } 

但是这是在一个JS文件中定义的。 而要使其在其他JS文件中可用,我必须导出此函数。 这是定义实体的最好方法,还是我可以用其他方式定义某种types的格式?

这对创build对象来说很好。 如果你开始使用像Mongo这样的数据库,那么使用mongoose创build对象也许更好,但这也是个人喜好。 至于你的例子 –

1)出口人员

 module.exports = Person; 

2)从另一个文件导入人员

 const Person = require('../path/to/Person'); 

3)使用new关键字创build人员来调用构造函数(非常重要)

 const mitch = new Person('Mitch'); 

你应该阅读javascript's prototype 。 每个对象都有对Object.prototype的引用。 然后,你可以用Object.create(obj)创build对象来创build对象,并将新对象的原型作为被传递给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.'