|
Subject:
|
Inheritance issues
|
|
Posted By:
|
filip
|
Post Date:
|
8/17/2006 9:25:07 AM
|
Let's consider this example (p.112-113)
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 defined things in the Triangle function?
2/ "Triangle.prototype = new Polygon();" : Won't this same line assign this.sides to 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 and try to be as compete as possible?
|
|
Reply By:
|
nzakas
|
Reply Date:
|
8/25/2006 9:46:13 PM
|
1) No it doesn't. The things defined in the Triangle() function are applied after the changes to the prototype object. It's a little bit confusing because the code is arranged the way it is, but keep in mind that changes to the prototype take effect immediately while changes inside of a function take effect only when the function is called.
2) This will assign sides to be equal to undefined. You don't want to pass in any default values because you want your constructor, Triangle, to supply them.
Nicholas C. Zakas Author, Professional JavaScript for Web Developers (ISBN 0764579088) http://www.nczonline.net/
|