2016-05-17 122 views
1

有人可以請解釋什麼是正確的方法是讓多個對象從父項繼承並有自己的原型功能?我試圖在nodeJS中做到這一點。JavaScript繼承對象覆蓋其他繼承對象

我有這些文件。

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; 

現在我需要他們兩個在我的節點應用

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行後您將某個* else *分配給'ParserA.prototype'。爲什麼? – Pointy

回答

2

這是因爲它們指的是相同的原型對象。

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

刪除這兩行(覆蓋它們上面的兩行),你會很好。

+0

是的。 'ParserA.prototype = Object.create(ParentParser.prototype)'已經負責將ParentParser的原型添加到ParserA的原型鏈中。 –

+1

是的,完全正確。有時你看不到樹林。那條單線確實覆蓋了另一個函數。感謝指針。 – Ron