08.01.2015 Views

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

Beginning Web Development, Silverlight, and ASP.NET AJAX

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.

342<br />

CHAPTER 14 ■ JAVASCRIPT PROGRAMMING WITH <strong>ASP</strong>.<strong>NET</strong> <strong>AJAX</strong><br />

Going back to our boat sample, we can now build an interface for all powered vehicles,<br />

which could be implemented by a motorcycle or an aircraft. If SpeedBoat implements<br />

this interface, then the prototypes for the engine functions are available to it.<br />

First of all, you declare an interface as a prototyped set of JavaScript functions that<br />

you then register as interfaces using the registerInterface comm<strong>and</strong>. Here’s an example:<br />

Vehicles.IPowered = function() {}<br />

Vehicles.IPowered.Prototype = {<br />

checkFuel: function(){}<br />

}<br />

Vehicles.IPowered.registerInterface('Vehicles.IPowered');<br />

This creates <strong>and</strong> registers an interface called Vehicles.IPowered. So, if you want to<br />

make SpeedBoat implement this interface, you use the registerClass call. Earlier, when<br />

you registered the SpeedBoat class, you did it like this:<br />

Vehicles.SpeedBoat.registerClass('Vehicles.SpeedBoat', Vehicles.Boat);<br />

To change this to implement the interface, you use the interface name as the third<br />

parameter, like this:<br />

Vehicles.SpeedBoat.registerClass('Vehicles.SpeedBoat', Vehicles.Boat,<br />

Vehicles.IPowered);<br />

Now if you want to use the function, you must implement an override within the<br />

SpeedBoat class, or just use the base declaration from the interface. Here’s an example of<br />

overriding:<br />

Vehicles.SpeedBoat.prototype = {<br />

checkFuel: function(){<br />

return "Yes, I use <strong>and</strong> need fuel, because I implement IPowered";<br />

}, ...<br />

}<br />

As you can imagine, your code can get pretty complex if you are defining large hierarchies<br />

of classes <strong>and</strong> using interfaces <strong>and</strong> inheritance to have coherent functionality<br />

across the set. In many cases, you would need to have an object check to see if it implements<br />

a certain interface or inherits from a certain class before invoking a method, in<br />

case it isn’t implemented <strong>and</strong> you get an error. This is where reflection, the process of<br />

examining the structure of a component at runtime, comes in h<strong>and</strong>y.

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

Saved successfully!

Ooh no, something went wrong!