Kann jemand bitte erklären, was der richtige Weg ist, um mehrere Objekte von einem Elternteil erben und haben ihre eigenen Prototyp-Funktionen? Ich versuche dies in NodeJS zu tun.JavaScript geerbt Objekt überschreibt andere geerbtes Objekt
Ich habe diese Dateien.
ParserA_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');
}
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
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;
Jetzt habe ich sie beide in meinem Knoten App benötigen
var ParserA = require('ParserA_file');
var ParserB = require('ParserB_file');
Jetzt
, wenn nur ein Parser geladen wird das kein Problem, aber sie beide in meinem Knoten App laden und starten Parser eine
var parser = new ParserA(this, file);
parser.startParse()
kehrt
init --- INIT 'parser_B' parser'
Jetzt für die Frage, Wie kommt es, dass die Funktion startParse
von ParserB die startParse
von ParserA überschreibt?
Sie ordnen etwas dem 'ParserA.prototype' zu, und dann ordnen Sie 2 Zeilen später * else * dem' ParserA.prototype' zu. Warum? – Pointy