8.3 Manipulating Objects


8.3.1 The with Keyword

The with keyword is used as a kind of shorthand for referencing an object's properties or methods .

The object specified as an argument to with becomes the default object for the duration of the block that follows . The properties and methods for the object can be used without naming the object. (If a method is used, don't forget to include the parentheses after the method name .)

FORMAT

 
 with (object){     < properties used without the object name and dot> } 

Example:

 
 with(employee){     document.write(name, ssn, address); } 
Example 8.9
 <html>     <head><title>The with Keyword</title>     <script language = "javascript"> 1  function book  (title, author, publisher){ 2           this.title = title;   //  Properties  this.author = author;             this.publisher = publisher; 3  this.show = display;  //  Define a method  } 4  function display  (anybook){ 5  with(this)  {   //  The with keyword  6              var info = "The title is " +  title  ;                info += "\nThe author is " +  author  ;                info += "\nThe publisher is " +  publisher  ; 7  alert(info);  }         }     </script>     </head>     <body bgcolor="lightblue">     <script language = "javascript"> 8  var childbook = new book  ("A Child's Garden of Verses",                                  "Robert Lewis Stevenson",                                  "Little Brown"); 9  var adultbook = new book  ("War and Peace",                                  "Leo Tolstoy",                                  "Penguin Books"); 10  childbook.show(childbook);  //  Call method for child's book  11  adultbook.show(adultbook);  //  Call method for adult's book  </script>     </body>     </html> 

EXPLANATION

  1. The book constructor function is defined with its properties.

  2. The book object is described with three properties: title, author , and publisher .

  3. The book object's property is assigned the name of a function. This property will serve as a method for the object.

  4. A function called display is defined.

  5. The with keyword will allow you to reference the properties of the object without using the name of the object or the this keyword. (See "The Math Object" on page 172 in Chapter 9.)

  6. A variable called info is assigned the property values of a book object. The with keyword allows you to specify the property name without a reference to the object (and dot) preceding it.

  7. The alert box displays the properties for a book object.

  8. The constructor function is called and returns an instance of a new book object called childbook .

  9. The constructor function is called and returns an instance of another book object called adultbook .

  10. The show() method is called passing a reference to the childbook object.

  11. The show() method is called passing a reference to the adultbook object.

Figure 8.9. The childbook object and its properties.

graphics/08fig09.jpg

Figure 8.10. The adultbook object and its properties.

graphics/08fig10.jpg

8.3.2 The for/in Loop

JavaScript provides the for/in loop, which can be used to iterate through a list of object properties or array elements. The for/in loop reads: for each property in an object (or for each element in an array) get the name of each property (element), in turn , and for each of the properties (elements), execute the statements in the block that follows.

The for/in loop is a convenient mechanism for looping through the properties of an object.

FORMAT

 
 for(var property_name in object){     statements; } 
Example 8.10
 <html>     <head><title>User-defined objects</title>         <script language = "javascript"> 1  function book(title, author, publisher)  { 2              this.title = title;                this.author = author;                this.publisher = publisher; 3  this.show=showProps;  //  Define a method for the object  } 4  function showProps(obj, name)  {             //  Function to show the object's properties  var result = ""; 5  for (var prop in obj)  { 6                 result += name + "  .  " +  prop  + " = " +  obj[prop]  + "<br>";                } 7              return result;             }         </script>     </head>     <body bgcolor="lightblue">         <script language="javascript"> 8  myBook = new book("JavaScript by Example", "Ellie",   "Prentice Hall");  9           document.write("<br><b>" +  myBook.show(myBook, "myBook"  ));         </script>     </body>     </html> 

EXPLANATION

  1. The function called book will define the properties and methods for a book object. The function is a template for the new object. An instance of a new book object will be created when this constructor is called.

  2. This is the first property defined for the book object. The this keyword refers to the current object.

  3. A function name called showProps is assigned to a property of the object, thus creating a method for the object.

  4. The function called showProps is defined, tasked to display all the properties of the object.

  5. The special for/in loop executes a set of statements for each property of the object.

  6. The name and value of each property is concatenated and assigned to a variable called result. obj[prop] is used to key into each of the property values of the book object.

  7. The value of the variable result is sent back to the caller. Each time through the loop, another property and value are displayed.

  8. A new book object called myBook is created ( instantiated ).

  9. The properties for the book object are shown in the browser window; see Figure 8.11. Notice how the method and its definition are displayed.

    Figure 8.11. The book object's properties.

    graphics/08fig11.jpg

8.3.3 Extending Objects with Prototypes

Object-oriented languages support a feature called inheritance, where one object can inherit the properties of another. JavaScript implements inheritance with prototypes. As of Netscape Navigator 3.0, it is possible to add properties to objects after they have been created by using the prototype object.

JavaScript functions are automatically given an empty prototype object. If the function serves as the constructor for an object, then the prototype object can be used to implement inheritance. When the properties are assigned to a given object by a constructor function, the prototype object gets the same properties. Each time a new object of the same class is created, that object also inherits the prototype object and all the same properties. The good news is that even after an object has been created, it can be extended with new properties that will also become part of the prototype . Then any objects created after that will automatically inherit the new properties.

What Is a Class?

In object-oriented languages, the object's data describes the properties. The object, along with its properties and methods, is bundled up into a container called a class , and one class can inherit from another, and so on. Even though JavaScript doesn't have a class mechanism per se, it mimics the class concept with the constructor and its prototype object.

Each JavaScript class has a prototype object and one set of properties. Any objects created in the class will inherit the prototype properties. Let's say we define a constructor function called Employee() with a set of properties. The prototype object has all the same properties. The Employee() constructor function represents a class. The constructor is called and instantiates an object called janitor , and then the constructor is called again and instantiates another object called manager , and so on. Each instance of the Employee() class automatically inherits all the properties defined for the Employee through its prototype .

After an object has been created, new properties can be added with the prototype property. This is how JavaScript implements inheritance.

Example 8.11
 <html>     <head><title>User-defined objects and Inheritance</title>     <script language = "javascript"> 1  function Book  (title, author, publisher){    //  The Book class  this.title = title;             this.author = author;             this.publisher = publisher;             this.show=showProps;         } 2  function showProps  (obj,name){            var result = "";  for (var i in obj)  {  result += name + "." + i + " = " + obj[i] + "<br>";  }            return result;         }     </script>     </head>     <body bgcolor="lightblue">     <script language="javascript">     //  Add a new function  3  function lastEdition(){   this.latest=prompt("Enter the latest edition for   "+this.title,"");   return (this.latest);   }  //  Add a new property with prototype  4  Book.prototype.edition=lastEdition;  5  var myBook=new Book("JavaScript by Example", "Ellie",   "Prentice Hall");  //  Define a new method  document.write("<br><b>" + myBook.show(myBook,"myBook")+"<br>"); 6   document.write("The latest edition is "+  myBook.edition()  +"<br>");     </script>     </body>     </html> 

EXPLANATION

  1. The function called Book defines the properties and methods for a Book object. Book is a JavaScript class. Each object has a prototype whose properties it inherits. An instance of a new Book object will inherit all of these properties.

  2. A function called showProps is defined. It uses the special for loop to iterate through all the properties of an object. It will be used to create a method for the Book object, called show() .

  3. A function called lastEdition() is defined. It returns the latest edition of the book.

  4. A new property is given to the Book object using the prototype property, followed by the property name, edition . This property is assigned the name of a function called lastEdition , thus creating a new method for the Book class.

  5. A new Book object, called myBook , is created. It has inherited all of the original properties of the Book class, plus the new property defined by the prototype property, called edition .

  6. The new method is called for the myBook object.

Extending a JavaScript Object

Since all objects have the prototype object, it is possible to extend the properties of a JavaScript built-in object, just as we did for a user-defined object. (See Chapter 9, "JavaScript Core Objects.")

Example 8.12
 <html><head><title>Prototypes</title>     <script language = "javascript">  // Customize String Functions  1  function uc()  { 2           var str=this.big(); 3           return( str.toUpperCase());         } 4  function lc()  { 5           var str=this.small(); 6           return( str.toLowerCase());         } 7  String.prototype.bigUpper=uc;  8  String.prototype.smallLower=lc;  9       var string="This Is a Test STRING."; 10  string=string.bigUpper()  ;         document.write(string+"<br>"); 11      document.write(  string.bigUpper()  +"<br>"); 12      document.write(  string.smallLower()  +"<br>");     </script>     </head>     <body bgcolor="lightblue"></body>     </html> 

EXPLANATION

  1. A function called uc is defined. It will manipulate a String object.

  2. The big() method is an HTML method that will increase the font size (one size larger than the current font) for the String object.

  3. The string will be returned with a larger font and all letters in uppercase.

  4. A function called lc is defined. It will also manipulate the String object.

  5. The small() method is an HTML method that will decrease the font size (one size smaller than the current font) for the String object.

  6. The string will be returned with a smaller font and all letters in lowercase.

  7. The function uc is assigned to the String.prototype.bigUpper property, creating a new method for the String object.

  8. The function lc is assigned to the String.prototype.smallLower property, creating another new method for the String object.

  9. This is the String object that will be manipulated by the new methods created by the prototype property.

  10. When the string.bigUpper() method is called, the string is converted to uppercase with all letters in a bigger font.

  11. The string.bigUpper() method is called again, creating a larger string all in capital letters.

  12. When the string.smallLower() method is called, the string is converted to lowercase with all letters in a smaller font. See output in Figure 8.12.

    Figure 8.12. Extending properties to a built-in class. Output from Example 8.12.

    graphics/08fig12.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

Similar book on Amazon

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