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?
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?