How to override part of an overload function in JavaScript
- by Guan Yuxin
I create a class with a function like this
var Obj=function(){this.children=[];this.parent=null;}//a base class
Obj.prototype.index=function(child){
// the index of current obj
if(arguments.length==0){
return this.parent?this.parent.index(this):0;
}
// the index of a child matchs specific obj [to be override]
return -1;
}
basically it is just an overload function composed of index() and index(child).
Then I create a sub class,SubObj or whatever, inherits from Obj
SubObj.prototype.prototype=Obj;
Now, it's time to override the index(child) function,however, index() is also in the function an I don't want to overwrite it too.
One solution is to write like this
var Obj=function(){this.children=[];this.parent=null;}//a base class
Obj.prototype.index=function(child){
// the index of current obj
if(arguments.length==0){
return this.parent?this.parent.index(this):0;
}
// the index of a child matchs specific obj [to be override]
return this._index(this);
}
Obj.prototype._index=function(this){
return -1;
}
SubObj.prototype._index=function(this){/* overwriteing */}
But this will easily mislead other coders as _index(child) should be both private(should not be used except index() function) and public(is an overload function of index(),which is public)
you guys have better idea?