What are the ways of achieving inheritance in javascript. I am getting confused on the OOPS as i see different ways of doing the same thing.
Below is a simple parent/child
relationship.
function Plant () {
this.country = "Mexico";
this.isOrganic = true;
}
Plant.prototype.showNameAndColor = function () {
console.log("I am a " + this.name + " and my color is " + this.color);
}
Plant.prototype.amIOrganic = function () {
if (this.isOrganic)
console.log("I am organic, Baby!");
}
function Fruit (fruitName, fruitColor) {
this.name = fruitName;
this.color = fruitColor;
}
Fruit.prototype = new Plant ();
var aBanana = new Fruit ("Banana", "Yellow");
console.log(aBanana.name); // Banana
console.log(aBanana.showNameAndColor()); // I am a Banana and my color is yellow.
First Question:
I have seen in some codes there are setting the constructor of the children too, this makes me quite confusing?. Why do people also set Fruit.prototype.constructor = Plant;
Is the below code not enough to achieve inheritance
Fruit.prototype = new Plant(); // Fruit has all methods/properties of Plant Object
Second Question:
Passing values to Super
constructor.
Fruit.prototype = new Plant ("Aus", true);
OR
function Fruit (fruitName, fruitColor) {
Plant.call(this,"Aus", true);
this.name = fruitName;
this.color = fruitColor;
}
Why is the former always preferred than the later while passing arguments to parent constructor
?.