Accessing Class Members


this.Count = count; 

When you're working with class members, the most important aspect is to explicitly define all members. To allow external code to access the class members (properties and methods), the this keyword must be used. So if you define a function XYZ() within the class, it is available as a class method only if you add this code:

this.XYZ = XYZ; 


Within this method, you can also access class properties using this; however, they have to be defined as well. For accessing class members both internally and externally, the dot (.) is used to separate instance name and member name.

The following code implements a simple class. The only class method, Count() (internal name: count()), takes one parameter and then counts in the given language. Figure 6.1 shows the result.

A Class with Members (members.html)

<script language="JavaScript"   type="text/javascript"> function UniversalCounter() {   this.copyright = "(C) 2006 JavaScript Phrasebook";   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]);     } else {       window.alert("Unknown language");     }   } } var uc = new UniversalCounter(); uc.Count("fr"); </script> 

Figure 6.1. The "Universal Counter."


Note

Another way to create objects is to use the Object constructor, in the following fashion:

var uc = new Object(); uc.copyright = "(C) 2006 JavaScript Phrasebook "; uc.printCopyright = function() {   window.alert(this.copyright); }; 



Emulating Private Class Members

JavaScript does not have class modifiers like public, protected, and private that define who may access class members and who may not. However, as you can see in the previous phrase, there is quite an easy way to emulate private class members: If you do not "register" a variable or function within the class using the this keyword, it is visible only internally. In the previous phrase, the numbers object cannot be accessed from the outside, but is used internally by the Count()/count() method.





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