18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Inheritance<br />

The two highlighted lines in the previous code implement inheritance from the Polygon class for both<br />

the Triangle and the Rectangle classes. The reason this works is that the prototype object isn’t being<br />

overwritten when using the inheritFrom() method; methods are just being added to it. Using this<br />

method, it’s possible to get around the prototype chaining restriction and implement dynamic prototyping<br />

the way it is intended.<br />

Multiple Inheritance support<br />

One of the most useful features of the zInherit library is its capability to support multiple inheritance,<br />

which is not available using prototype chaining. Again, the key fact that makes this possible is that<br />

inheritFrom() doesn’t replace the prototype object.<br />

The inheritFrom() method must be used in combination with object masquerading in order to inherit<br />

properties and methods. Consider the following example:<br />

function ClassX() {<br />

this.messageX = “This is the X message. “;<br />

if (typeof ClassX._initialized == “undefined”) {<br />

ClassX.prototype.sayMessageX = function () {<br />

alert(this.messageX);<br />

};<br />

}<br />

}<br />

ClassX._initialized = true;<br />

function ClassY() {<br />

this.messageY = “This is the Y message. “;<br />

if (typeof ClassY._initialized == “undefined”) {<br />

ClassY.prototype.sayMessageY = function () {<br />

alert(this.messageY);<br />

};<br />

}<br />

}<br />

ClassY._initialized = true;<br />

Both ClassX and ClassY are small classes, each with one property and one method. Suppose you now<br />

have ClassZ that needs to inherit from both. The class can be defined like this:<br />

function ClassZ() {<br />

ClassX.apply(this);<br />

ClassY.apply(this);<br />

this.messageZ = “This is the Z message. “;<br />

if (typeof ClassZ._initialized == “undefined”) {<br />

ClassZ.prototype.inheritFrom(ClassX);<br />

ClassZ.prototype.inheritFrom(ClassY);<br />

119

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

Saved successfully!

Ooh no, something went wrong!