Setting Default Property Values


In NS4+ and IE4+, you can specify default values for properties in a constructor using this syntax, where the default value appears as the second term in each OR expression (which uses the JavaScript operator):

 function friend(name, phone, rank)  {  this.name = name  "George"   this.phone = phone  "555-1212"   this.rank = rank  10  } 

Now you can pass an empty string or null as an argument to this constructor, and the appropriate default value will be used instead. In fact, you can even omit arguments, and the constructor will apply the default value instead, as long as the default arguments are at the very end of the argument list you pass (so the constructor knows which arguments have been omitted). Here's an example where I'm omitting the "rank" argument in a call to this constructor when creating one object:

(Listing 23-07.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Creating Custom Objects          </TITLE>      </HEAD>      <BODY>          <H1>Creating Custom Objects</H1>          <FORM NAME="form1">              <TEXTAREA NAME="textarea1" ROWS="5" COLS="40"></TEXTAREA>          </FORM>          <SCRIPT LANGUAGE="JavaScript">              <!--             function friend(name, phone, rank)              {  this.name = name  "George"   this.phone = phone  "555-1212"   this.rank = rank  10  }              var array1 = new Array(4)              array1[0] = new friend("Ed", "555-1111", 4)              array1[1] = new friend("Harold", "555-2222", 1)              array1[2] = new friend("Nancy", "555-3333", 3)  array1[3] = new friend("Sandy", "555-4444")  for(var loopIndex = 0; loopIndex < array1.length; loopIndex++){                  document.form1.textarea1.value += "Name: " + array1[loopIndex].name + " "                  document.form1.textarea1.value += "Phone: " + array1[loopIndex].phone + " graphics/ccc.gif "                  document.form1.textarea1.value += "Rank: " + array1[loopIndex].rank + "\ graphics/ccc.gif n"              }              // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the results in Figure 23.8. Note the last entry for Sandyyou can see the default value for the rank property, 10, is set in that object.

Figure 23.8. Using default properties.

graphics/23fig08.gif

Besides adding properties to custom objects, you also can add methods . I'll take a look at that next .



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

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