SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Feb 2003
    Location
    eez
    Posts
    331
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Inheritance issues

    Hi!

    Let's consider this example:

    function Polygon(iSides) {
    this.sides = iSides;
    }

    Polygon.prototype.getArea = function () {
    return 0;
    };


    function Triangle(iBase, iHeight) {
    Polygon.call(this, 3);
    this.base = iBase;
    this.height = iHeight;
    }

    Triangle.prototype = new Polygon();
    Triangle.prototype.getArea = function () {
    return 0.5 * this.base * this.height;
    };


    Here are my questions:

    1/ "Triangle.prototype = new Polygon();" : Doesn't this line overwrite all the properties already defined in the Triangle function?

    2/ "Triangle.prototype = new Polygon();" : Won't this same line assign this.sides an empty string (or undefined ??) if one considers that the polygon function has no arguments? Or does writing ...prototype = new SomeClass() only "touch on" the methods?

    Thank you!!!

  2. #2
    SitePoint Addict
    Join Date
    Feb 2003
    Location
    eez
    Posts
    331
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    anyone?

  3. #3
    SitePoint Wizard Pepejeria's Avatar
    Join Date
    Jan 2005
    Location
    Too far up north
    Posts
    1,566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by aqw
    Here are my questions:

    1/ "Triangle.prototype = new Polygon();" : Doesn't this line overwrite all the properties already defined in the Triangle function?
    Yes, that is why you need to do this before adding methods to the Triangle class
    Quote Originally Posted by aqw
    2/ "Triangle.prototype = new Polygon();" : Won't this same line assign this.sides an empty string (or undefined ??) if one considers that the polygon function has no arguments? Or does writing ...prototype = new SomeClass() only "touch on" the methods?
    That part will be executed first, so sides will be undefined. Try this by alerting this.sides in the Polygon constructor.

    It will then be set to 3 when an instance of Triangle is created.

    You might wanna read this great article about doing inheritance in JavaScript.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •