我正在用节点js编写一个工具。我想在节点js中定义一些POJO。我在Node js方面没有多少经验。我来自JAVA背景,其中类用于定义实体。我现在定义实体的一种方法是:-
function Person(name) {
this.name = name;
this.values = [];
this.characteristics = {};
}但这是在一个JS文件中定义的。为了使它在其他JS文件中可用,我必须导出这个函数。这是定义实体的最佳方式,还是有其他方法可以定义类格式的东西?
发布于 2017-10-29 23:31:43
对于创建对象来说,这是很好的。如果您开始使用像mongo这样的DB,您最好用mongoose创建对象,但这也是个人偏好。至于你的例子-
1)出口人
module.exports = Person;2)从另一个文件中导入人
const Person = require('../path/to/Person');3)用new关键字创建Person来调用构造函数(非常重要)
const mitch = new Person('Mitch');你应该读一读javascript's prototype。每个对象都有一个对Object.prototype的引用。然后,您可以使用Object.create(obj)创建对象来创建对象,并将新对象的原型指定为传递给Object.create(obj)的引用
// 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.'https://stackoverflow.com/questions/47006288
复制相似问题