18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Inheritance<br />

Polygon.prototype.getArea = function () {<br />

return 0;<br />

};<br />

}<br />

}<br />

Next, rewrite the Triangle class, which is the first taste of real inheritance in this example:<br />

_classes.registerClass(“Triangle”, “Polygon”);<br />

function Triangle(iBase, iHeight) {<br />

_classes.defineClass(“Triangle”, prototypeFunction);<br />

this.init(iBase,iHeight);<br />

function prototypeFunction() {<br />

Triangle.prototype.init = function(iBase, iHeight) {<br />

this.parentMethod(“init”, 3);<br />

this.base = iBase;<br />

this.height = iHeight;<br />

};<br />

}<br />

Triangle.prototype.getArea = function () {<br />

return 0.5 * this.base * this.height;<br />

};<br />

}<br />

Note the registerClass() call just before the constructor, where the inheritance relationship is set up.<br />

Also, the first line of the init() method calls the superclass (Polygon) init() with an argument of 3,<br />

which sets the sides property to 3. Other than that, the init() method is very similar: a simple constructor,<br />

assigning the base and height.<br />

The Rectangle class ends up looking very similar to Triangle:<br />

_classes.registerClass(“Rectangle”, “Polygon”);<br />

function Rectangle(iLength, iWidth) {<br />

_classes.defineClass(“Rectangle”, prototypeFunction);<br />

this.init(iLength, iWidth);<br />

function prototypeFunction() {<br />

Rectangle.prototype.init = function(iLength, iWidth) {<br />

this.parentMethod(“init”, 4);<br />

this.length = iLength;<br />

this.width = iWidth;<br />

}<br />

123

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!