Inheriting Classes


UniversalCounter.prototype =   new UniversalTranslator(); 

JavaScript does not enjoy an inheritance system for classes. However, via use of the prototype keyword, something similar can beonce againemulated. With prototype, you can provide class members that are valid for all objects, including inherited ones. When JavaScript has to look up a property or method (for example, when object.methodname() will be executed), JavaScript first looks into the class and then looks into the prototype object. This allows some kind of inheritance.

In the following example, the UniversalTranslator class defines a member (copyright). Then, the UniversalCounter() class is implemented in a similar fashion as before. The following command sets the prototype property of the UniversalCounter class to a new instance of the UniversalTranslator class. Consequence: The UniversalCounter class inherits all properties of the UniversalTranslator class and can access it:

Class Inheritance with Prototype (inheritance.html)

<script language="JavaScript"   type="text/javascript"> function UniversalTranslator() {   this.copyright = "(C) 2006 JavaScript Phrasebook"; } function UniversalCounter() {   this.Count = count;   var numbers = {     "en": "one, two, three",     "fr": "un, deux, trois",     "de": "eins, zwei, drei"   };   function count(language) {     if (numbers[language]) {       window.alert(numbers[language] +         " [" + this.copyright + "]");     } else {       window.alert("Unknown language");     }   } } UniversalCounter.prototype =   new UniversalTranslator(); var uc = new UniversalCounter(); uc.Count("de"); </script> 

Figure 6.2 shows that this really works: The copyright property can be accessed from the UniversalCounter class although it is defined in the UniversalTranslator class.

Figure 6.2. The inherited class property is shown.


Warning

Only class members are inherited, but not class constructor code. If you want to do this as well, you have to define a specific method to be the class constructor, and call it manually in the derived class.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net