0

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)
  1. 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

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Ein2012
  • 1,103
  • 1
  • 13
  • 33
  • 1
    First of all this is not the way to do inheritance. You can set an object to prototype and you have just set the reference of shape function. And when you set the constructor function to Square you are just setting the reference of Square function. – Vaibhav Feb 21 '15 at 07:43
  • Maybe this answer can help you: http://stackoverflow.com/a/16063711/1641941 – HMR Feb 21 '15 at 08:44

0 Answers0