2016-05-17 15 views
1

親から継承した複数のオブジェクトを持ち、独自のプロトタイプ関数を持つ正しい方法は何か説明できますか?私はnodeJSでこれをやろうとしています。Javascript継承オブジェクトは他の継承オブジェクトを上書きします

私はこれらのファイルを持っています。

ParserA_file

ParentParser = function(controller, file) { 

    if (!controller) { 
     throw (new Error('Tried to create a Parser without a controller. Failing now')); 
     return; 
    } 
    if (!file) { 
     throw (new Error('Tried to create a Parser without a file. Failing now')); 
     return; 
    } 
    this.controller = null; 
    this.file = null; 

} 

module.exports = ParentParser; 

は、今私は私のノードのアプリでそれらの両方を必要とParserB_file

var ParentParser = require('ParentParser_file'); 

module.exports = ParserB; 
ParserB.prototype = Object.create(ParentParser.prototype); 
ParserB.prototype.constructor = ParserB; 
ParserB.prototype = ParentParser.prototype; 

function ParserB(controller, file) { 
    ParentParser.call(this, controller, file); 
    this.controller.log('init --- INIT \'parser_B\' parser'); 
    this.date_regex = /([0-9]{1,2})?([A-Z]{3})?([0-9]{2})? ?([0-9]{2}:[0-9]{2})/; 
    this.date_regex_numeric = /(([0-9]{1,2})([0-9]{2})([0-9]{2}))? ?([0-9]{2}:[0-9]{2})?/; 
    this.date_format = 'DDMMMYY HH:mm'; 
} 

ParserB.prototype.startParse = function() { 
    console.log('Starting parse for B'); 
} 

ParentParser_file

var ParentParser = require('ParentParser_file'); 

module.exports = ParserA; 
ParserA.prototype = Object.create(ParentParser.prototype); 
ParserA.prototype.constructor = ParserA; 
ParserA.prototype = ParentParser.prototype; 

function ParserA(controller, file) { 
    ParentParser.call(this, controller, file); 
    this.controller.log('init --- INIT \'parser_A\' parser'); 
    this.date_regex = /([0-9]{1,2})?([A-Z]{3})?([0-9]{2})? ?([0-9]{2}:[0-9]{2})/; 
    this.date_regex_numeric = /(([0-9]{1,2})([0-9]{2})([0-9]{2}))? ?([0-9]{2}:[0-9]{2})?/; 
    this.date_format = 'DDMMMYY HH:mm'; 
} 

ParserA.prototype.startParse = function() { 
    console.log('Starting parse for A'); 
} 

var ParserA = require('ParserA_file'); 
var ParserB = require('ParserB_file'); 
一つだけパーサがロードされたとき

は今、何の問題は、しかし、私のノードのアプリにそれらの両方をロードすると、質問のための今すぐ

var parser = new ParserA(this, file); 
parser.startParse() 

戻り

init --- INIT 'parser_B' parser' 

パーサを開始、ありません、どのようにParserBの関数startParseがParserAからstartParseを上書きしますか?

+0

あなたは 'ParserA.prototype'に何かを割り当て、2行後に' ParserA.prototype'に* else *を割り当てます。どうして? – Pointy

答えて

2

これは、同じプロトタイプオブジェクトを参照するためです。

ParserA.prototype = ParentParser.prototype; 
... 
ParserB.prototype = ParentParser.prototype; 
ParserA.prototype === ParserB.prototype; // true 

(とにかく、その上の2行を上書きしている)、これらの2つの行を削除し、あなたが行ってもいいでしょう。

+0

'ParserA.prototype = Object.create(ParentParser.prototype)'は既にParserAのプロトタイプチェーンにParentParserのプロトタイプを追加して処理します。 –

+1

はい、まったく正しい。時々、木の森を見ることができません。その単一の行は実際に他の関数を上書きしました。ポインタありがとう。 – Ron

関連する問題