For the below code, that creates inheritance hierarchy,
function Animal(){
this.name = "Animal";
// toString is a function in the main Object that every
// object inherits from
this.toString = function() {
return "My name is : " + this.name;
};
}
function Rodent(){
this.name = "Rodent";
}
function Rat(){
this.name = "Rat";
}
Rodent.prototype = new Animal();
Rat.prototype = new Rodent();
Rodent.prototype.constructor = Rodent;
Rat.prototype.constructor = Rat;
var caneRat = new Rat();
document.write(caneRat.toString() + "<br />");
a little modification is done by completely replacing Rat.prototype
with Rodent.prototype
, as a second approach, shown below,
function Animal(){
this.name = "Animal";
// toString is a function in the main Object that every
// object inherits from
this.toString = function() {
return "My name is : " + this.name;
};
}
function Rodent(){
this.name = "Rodent";
}
function Rat(){
this.name = "Rat";
}
Rodent.prototype = new Animal();
Rat.prototype = Rodent.prototype;
Rodent.prototype.constructor = Rodent;
var caneRat = new Rat();
document.write(caneRat.toString() + "<br />");
What are the advantages & disadvantages in the second approach of inheritance hierarchy design compared to first approach? Second approach is visualized as shown below..
Rat
andRodent
don't inherit from each other. – Bergi Dec 8 '15 at 4:02new
at all for creating prototype objects. – Bergi Dec 8 '15 at 4:53new
keyword for prototype objects for first approach? – overexchange Dec 8 '15 at 5:05