JavaScript
  Home arrow JavaScript arrow Page 4 - Object-Oriented JavaScript: Using the `Pro...
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Moblin 
JMSL Numerical Library 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Object-Oriented JavaScript: Using the `Prototype` Property
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 13
    2005-12-05

    Table of Contents:
  • Object-Oriented JavaScript: Using the `Prototype` Property
  • Prototyping objects: looking at the “prototype” property
  • Object interaction in JavaScript: applying Inheritance through the “prototype” property
  • Traversing object properties: using the “for in” loop structure

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Object-Oriented JavaScript: Using the `Prototype` Property - Traversing object properties: using the “for in” loop structure


    (Page 4 of 4 )

    One of the most common tasks performed when working with user-defined objects is naturally utilizing their properties in some way. After all, what’s the point of assigning properties to an object if they won’t be used at all? Fortunately, JavaScript offers a special statement, the “for in” loop, that allows you to easily iterate over all the properties of an object without having to write customized code to accomplish the task. Its basic signature is the following:

    for(var object_properties in object_name){
        // code to process object properties
    }

    As you can see, the “for in” loop uses two variables for traversing the properties of an object. The first one is utilized as an index, while the second one is the variable that holds the object itself. Now, in order to demonstrate the functionality of this statement, I’ll use the “Div” constructor function shown previously to create a new object and utilize a “for in” loop for iterating over the object’s properties. The example looks like this:

    function Div(w,h,t,l,p,bg){
        // define object properties
        this.div=document.createElement('div');
        this.w=w+'px';
        this.h=h+'px';
        this.pos='absolute';
        this.top=t+'px';
        this.left=l+'px';
        this.pad=p+'px';
        this.bord='1px solid #000';
        this.bg='#'+bg;
        // define 'display()' method
        this.display=function(){
            this.div.style.width=this.w;
            this.div.style.height=this.h;
            this.div.style.position=this.pos;
            this.div.style.top=this.top;
            this.div.style.left=this.left;
            this.div.style.padding=this.pad;
            this.div.style.border=this.bord;
            this.div.style.background=this.bg;
            document.getElementsByTagName('body')[0].appendChild(this.div);
        }
    }

    Having defined the constructor function for “Div” objects, the next step consists of defining a simple wrapping function, which internally uses a “for in” loop, in order to iterate over the properties of the object just created. Take a look at the example below:

    function displayObjProp(obj){
        var div=document.createElement('div');
        for(var i in obj){
            var p=document.createElement('p');
            p.appendChild(document.createTextNode('Name :'+i+' Value :'+obj[i]));
            div.appendChild(p);
        }
        document.getElementsByTagName('body')[0].appendChild(div);
    }

    // instantiate div object
    var div=new Div(400,250,100,100,5,'00f');
    div.display();
    // call 'displayObjProp()' function
    displayObjProp(div);

    After running the above script, the “displayObjProp()” function loops over the properties of the div object and displays their name/value pairs, outputting the corresponding values in the following format:

    Name :div Value :[object HTMLDivElement]
    Name :w Value :300px
    Name :h Value :250px
    Name :pos Value :absolute
    Name :top Value :100px
    Name :left Value :100px
    Name :pad Value :5px
    Name :bord Value :1px solid #000
    Name :bg Value :#00f
    Name :display Value : function () { this.div.style.width = this.w; this.div.style.height = this.h; this.div.style.position = this.pos; this.div.style.top = this.top; this.div.style.left = this.left; this.div.style.padding = this.pad; this.div.style.border = this.bord; this.div.style.background = this.bg; document.getElementsByTagName("body")[0].appendChild(this.div); }

    As you can appreciate, the output generated by the simple script shows the complete list of properties attached to the div object in the form “property name/property value.” Notice how the “display()” method is also listed, as part of the object’s properties. This reaffirms the concept that you learned in the first part of the series, where I demonstrated how properties can hold plain values, functions or even other objects.

    To wrap up

    At this stage, my journey exploring the creation and implementation of user-defined objects in JavaScript has almost finished. But, this isn’t a definitive goodbye. After showing some simple examples, which hopefully have demonstrated the nice capabilities of JavaScript for working with custom objects, there is still one step further to go. It’s precisely for that reason that over the last part of the series, I’ll write some constructor functions that can be used in real-word applications, in order to work with HTTP requester objects and pop-ups constructors. So, get ready for the next coding challenge!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This second tutorial explores the specific use of the "prototype" property, in order...
       · Great tutorial, it explains the prototype property very well!
       · Thank you for your positive commments on my article. I truly appreciate that and...
       · Its really a great article, but it does not explains the mechanics of constructors...
       · Thank you for commenting on my JavaScript article. With regard to your first...
       · After struggeling with many arcane explanations I found your example demonstrated...
       · Hi Stephen,Thank you for the kind comments on my JavaScript article, and I’m...
     

    JAVASCRIPT ARTICLES

    - Using Mod_Security to Protect Your Server
    - Detecting and Countering Server Intrusions
    - Securing Your Web Server
    - Building a Secure Web Server
    - Protecting the Server
    - Book Review: Learning the Yahoo! User Interf...
    - Dynamically Generate a Selection List in a R...
    - Intergrate DWR into Your Java Web Application
    - Detect Browser Compatibility with the Reques...
    - Using the EXT JS Date Picker Widget
    - Ajax Hack for Entering Information Without R...
    - EXT JS 2.1 Overview
    - Using the Style Object for Zebra Tables with...
    - Binary Searching
    - An Improved Approach to Building Zebra Tables






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT