Adding Properties to Existing Objects


You also can add properties to existing objects in JavaScript, just by assigning such properties values as if those properties existed. To do this, the object you're working with must be a real object, which means you must create it with the new operator.

Here's an example. In this case, I'll create a new string with a greeting in it, add a new property named purpose to the string, and set the string's purpose to "greeting" :

 var string1 = new String("Hello from JavaScript!")  string1.purpose = "greeting"          .          .          . 

Here's an example that uses this code and displays the value of the new property in a text field:

(Listing 23-12.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Creating Custom Properties for Existing Objects          </TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--  function display()   {   var string1 = new String("Hello from JavaScript!")   string1.purpose = "greeting"   document.form1.text1.value = "The string's purpose is to be a " + string1. graphics/ccc.gif purpose   }  // -->          </SCRIPT>      </HEAD>      <BODY>          <H1>Creating Custom Properties for Existing Objects</H1>          <FORM NAME="form1">  <INPUT TYPE="TEXT" NAME="text1" SIZE="40">   <BR>   <INPUT TYPE="BUTTON" ONCLICK="display()" VALUE="Get Custom Property Value">  </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 23.12, where we've added a property to an existing object.

Figure 23.12. Adding a property to an existing object.

graphics/23fig12.gif



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