Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  23] [ 1]  / answers: 1 / hits: 27264  / 13 Years ago, mon, november 7, 2011, 12:00:00

How can I go about making a child class override a privileged method of a base class?



If its not possible, is there another way to achieve what I am trying to accomplish in the simple code example below?



I cannot convert the baseclass function parseXML() to public because it requires access to private variables



    function BaseClass()
{
var map = {};

// I cannot make this function public BECAUSE it accesses & changes private variables
this.parseXML = function( key, value )
{
alert(BaseClass::parseXML());
map[key] = value;
}
}

function ChildClass()
{
BaseClass.call(this);
this.parseXML = function( key, value, otherData )
{
alert(ChildClass()::parseXML());

// How can I call the base class function parseXML()?
//this.parseXML(); // calls this function not the parent function
//MyClass.prototype.doStuff.call
BaseClass.prototype.parseXML.call(this, key, value); // fails
//BaseClass.prototype.parseXML(); // fails

// perform specialised actions here with otherData
}
}

ChildClass.prototype = new BaseClass;

var a = new ChildClass();
a.parseXML();

More From » inheritance

 Answers
30
function BaseClass() {
var map = {};
this.parseXML = function(key, value) {
alert(BaseClass::parseXML());
map[key] = value;
}
}

function ChildClass() {
BaseClass.call(this);
var parseXML = this.parseXML;
this.parseXML = function(key, value, otherData) {
alert(ChildClass()::parseXML());
parseXML.call(this, key, value);
}
}

ChildClass.prototype = new BaseClass;

var a = new ChildClass();
a.parseXML();


Live Example



Basically you cache the privileged method (which is only defined on the object) and then call it inside the new function you assign to the privileged method name.



However a more elegant solution would be:



function BaseClass() {
this._map = {};
};

BaseClass.prototype.parseXML = function(key, value) {
alert(BaseClass::parseXML());
this._map[key] = value;
}

function ChildClass() {
BaseClass.call(this);
}

ChildClass.prototype = Object.create(BaseClass.prototype);
ChildClass.prototype.parseXML = function(key, value, otherData) {
alert(ChildClass()::parseXML());
BaseClass.prototype.parseXML.call(this, key, value);
}

var a = new ChildClass();
a.parseXML();


Live Example



Also bonus implementation using pd


[#89271] Friday, November 4, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsleyashlynnh

Total Points: 64
Total Questions: 119
Total Answers: 98

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;