In the following code, orange
's constructor logs as its parent's constructor (Plant()
) as opposed to Fruit()
which is its. Why is this so?
(Sorry about the random objects. It's the middle of the night and I'm just learning some JavaScript. Didn't think too much about them to make sense in the real world, just typed them in as samples to understand prototypes better.)
function Plant(name, colour) {
this.name = name;
this.colour = colour;
}
Plant.prototype.print = function () {
return "I'm a " + this.name.toLowerCase() + " and I'm " + this.colour.toLowerCase() + ".";
}
var mango = new Plant("Mango", "Orange");
console.log(mango.constructor);
function Fruit(type, isOrganic) {
this.type = type;
this.isOrganic = isOrganic;
}
Fruit.prototype = new Plant("Orange", "Orange");
var orange = new Fruit("staples", true);
console.log(orange.constructor);
I get a Plant(name, colour)
for both console.log() calls whereas I think I should be getting Fruit(type, isOrganic) for the second one. What am I doing/understand incorrectly?
http://jsfiddle.net/eHZf8/
Update: Consistent with the above, if I do the following...
Fruit.prototype = {
hello: "World"
};
...instead of what I did in the example above, I get Object()
as the constructor for the object even though I create it with new Fruit()
.
Why is it that an object's constructor property contains the oldest function in the lineage that was used to build it as opposed to the latest?
JS is a Prototype-based language. Objects aren't made and don't behave exactly the same as in Object Oriented languages.
What this means is that when you call...
Fruit.prototype = new Plant("Orange", "Orange");
You are defining that the Fruit "class" (though there aren't classes) is exactly the same as a Plant with with name => "Orange" and color => "Orange". Everything is copied, including the constructor.
Besides the problem of all Fruit now being oranges, one way to fix this would be to include this line...
function Fruit(type, isOrganic) {
this.type = type;
this.isOrganic = isOrganic;
}
Fruit.prototype = new Plant("Orange", "Orange");
Fruit.prototype.constructor = Fruit; // <--- Add this
Which makes Fruit use the Fruit() function as the constructor. Which is also passed down to all objects constructed with it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With