如何在Node.js的模块中使用Object.create进行inheritance
我有一个包含一般车辆信息的模块车辆。 我有另外一个模块Car,它为Vehicle对象增加了更多的function。
// Pseudo code only. The final functions do not have to resemble this var vehicle = require('vehicle') vehicle.terrain = 'Land' var car = vehicle.createCar() // car and anotherCar will have unique Car-related values, // but will use the same Vehicle info var anotherCar = vehicle.createCar()
我正在寻找使用Object.create Car模块,但不知道Object.create调用应该去的地方。
- 我应该在Car模块中有一个构造函数,它需要一个Vehicle对象的实例,并以Vehicle实例为原型执行Object.create?
- 或者,Object.create是否应该在Vehicle对象的函数中发生,比如createCar? 我的问题是,汽车应该关心它是从车辆派生出来的,汽车不应该知道汽车需要的。
- 或者即使Object.create是正确的方法。
请,任何示例和最佳做法将不胜感激。
更新:
我改变了这个例子,以更好地反映我正试图解决的inheritance问题。
您正在描述一个生成器模式,而不是inheritance我认为 – 我不会使用object.create这个。 VehicleBuilder负责构build具有与之相关的特定属性的对象。
var builder = new VehicleBuilder(); builder.terrain = 'Land'; builder.wheelCount = 2; builder.color = "blue"; var motorcycle = builder.createVehicle();
它可能使用类似于:
VehicleBuilder.prototype.createVehicle = function(){ var me = this; return new Vehicle({ color: me.color, terrain: me.terrain, wheelCount: me.wheelCount }); }
如果您看一下js中的典型inheritance模式,那么它的定义就会更加清晰,并在节点中使用两种主要模式。 一个是util.inherits。 它的代码很简单: https : //github.com/joyent/node/blob/master/lib/util.js#L423-428
exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false } }); };
第二个是在子类构造函数中调用父构造函数。
function ChildClass(){ SuperClass.call(this); // here }
例如: https : //github.com/joyent/node/blob/master/lib/stream.js#L25-28
因此,不是在构造函数中携带一堆属性或其他对象,而是使用原型链和构造函数来定义自定义子类的行为。
我会推荐一个不同的方法
// foo.js var topic = require("topic"); topic.name = "History"; topic.emit("message"); topic.on("message", function() { /* ... */ }); // topic.js var events = require("events"); var Topic = function() { }; // inherit from eventEmitter Topic.prototype = new events.EventEmitter(); exports.module = new Topic;
你有一个很好的EventEmitter
为你做消息传递。 我build议你只用它来扩展Topic
的原型。
为什么不只是使用js原生的基于原型的inheritance? 直接使用module.exports公开构造函数:
//vehicle.js module.exports = function() { //make this a vehicle somehow }
然后:
// Pseudo code only. The final functions do not have to resemble this var Vehicle = require('vehicle') Vehicle.terrain = 'Land' var car = new Vehicle() // car and anotherCar will have unique Car-related values, // but will use the same Vehicle info var anotherCar = new Vehicle()