Javascriptinheritance对象覆盖其他inheritance对象
有人可以请解释什么是正确的方法是从父母inheritance多个对象,并有自己的原型function? 我试图在nodeJS中做到这一点。
我有这些文件。
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})?([AZ]{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})?([AZ]{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');
现在,只有一个parsing器被加载时,没有任何问题,但是,将它们加载到我的节点应用程序中并启动parsing器A
var parser = new ParserA(this, file); parser.startParse()
回报
init --- INIT 'parser_B' parser'
现在对于这个问题,ParserB的函数startParse
如何覆盖startParse
的startParse?
那是因为他们指的是同一个原型对象。
ParserA.prototype = ParentParser.prototype; ... ParserB.prototype = ParentParser.prototype; ParserA.prototype === ParserB.prototype; // true
删除这两条线(无论如何都覆盖了它们上面的两条线),你会很好。