1

一般的な車両情報を含むモジュール Vehicle があります。Vehicle オブジェクトに機能を追加する別のモジュール Car があります。

// 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()

Car モジュールに Object.create を使用することを考えていますが、Object.create の呼び出し先がわかりません。

  • Vehicle オブジェクトのインスタンスを取得し、Vehicle インスタンスをプロトタイプとして Object.create を実行するコンストラクタを Car モジュールに含める必要がありますか?
  • それとも、createCar のように、Vehicle オブジェクトの関数で Object.create を実行する必要がありますか? この方法に関する私の問題は、Car が Vehicle から派生したものであることを気にする必要があることです。
  • または、 Object.create が正しいアプローチである場合でも。

例やベスト プラクティスを教えていただければ幸いです。

アップデート:

解決しようとしている継承の問題をよりよく反映するように例を変更しました。

4

3 に答える 3

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 に答える