1

我有一个模块 Vehicle ,其中包含一般车辆信息。我有另一个模块 Car,它为 Vehicle 对象添加了更多功能。

// 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?我对这种方式的问题是,Car 应该关心它是从 Vehicle 派生的,Vehicle 不应该知道 Car 需要它。
  • 或者即使 Object.create 是正确的方法。

请,任何示例和最佳实践将不胜感激。

更新:

我更改了示例以更好地反映我正在尝试解决的继承问题。

4

3 回答 3

4

imo,我认为您描述的是构建器模式而不是继承-我不会为此使用 object.create 。VehicleBuilder 负责构建具有与其关联的某些属性的对象。

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 中的典型继承模式,它的定义要好得多,并且在 node.js 中使用了两种主要模式。一个是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

因此,您可以使用原型链和构造函数来定义自定义子类行为,而不是车辆在其构造函数中获取一堆属性或另一个对象。

于 2011-05-26T02:15:00.970 回答
0

我会推荐一种不同的方法

// 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为您传递消息。我建议你只用它扩展原型Topic

于 2011-05-23T08:07:22.060 回答
0

为什么不直接使用基于 js 原生原型的继承呢?使用 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()
于 2011-05-26T01:18:22.460 回答