I'm new to JavaScript i'm trying wrap my head to understand about prototype and constructor.I have written small code and i can't deduce any thing out of it .
function shape() {
this.name = "shape";
this.toString = function() {
return this.name;
}
}
function Rectangle(w, h) {
this.name = "Rectangle";
this.width = w;
this.height = h;
this.area = function() {
return (2 * (this.width + this.height));
}
}
function Square(side) {
this.name = "Square";
this.area = function() {
return (side * side);
}
}
rect = new Rectangle(10, 20);
sq = new Square(100);
rect.constructor //gives Rectangle(w, h)
This means that the rect object is an instance created from Rectangle() constructor function
But the interesting part is that when i write the following line
rect.constructor=Square;
rect.prototype=shape;
rect.constructor //gives Square(side)
I have referenced prototype to shape , means i have inherited the properties of shape
var hybrid=new rect.constructor(); hybrid.name //gives "Square"
Now from rect object i can create an object with Square() constructor(template) ,and also can access the properties of shape through prototype and also access the rectangle properties of its own.But i don't understand the constructor part
Why java Script allows such robust syntax . Is there any practical advantages and also can correct me if i wrong anywhere in my above statements