SunQuest
 
       JavaScript
  Home arrow JavaScript arrow Page 2 - Object-Oriented JavaScript: An Introductio...
IBM developerWorks
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  
Dedicated Servers  
Actuate Whitepapers 
Moblin 
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: An Introduction to Core Concepts
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 19
    2005-11-28

    Table of Contents:
  • Object-Oriented JavaScript: An Introduction to Core Concepts
  • Working with objects in JavaScript : introducing the key concepts
  • Coupling methods to objects: defining self-contained constructors
  • Functions and objects: a closer look at the “Function” object
  • Getting information about objects: looking at the “constructor” property

  • 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

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Object-Oriented JavaScript: An Introduction to Core Concepts - Working with objects in JavaScript : introducing the key concepts


    (Page 2 of 5 )

    In order to introduce you to object-based programming in JavaScript, let’s go over the basics quickly. First, let me refresh some core concepts that play a crucial role when working with objects. Specifically, JavaScript conceives objects as a collection of properties, even when this collection can also contain functions (known as methods) or other objects.

    Widely known, JavaScript has a lot of built-in objects, which you’ve probably used many times. “Window”, “document”, and “Array” are good examples of the predefined objects available in the JavaScript universe, which should be familiar to you. However, as I mentioned earlier, the ability of JavaScript to create user-defined objects is actually where I’ll focus my attention. Therefore let me illustrate the process for defining custom objects. To begin with, I’ll use a sample “createDivs()” function, handy for building DIV elements on the fly, and later I’ll show you how to use the skeleton of this function for creating DIV objects. Here’s the definition for this function:

    function createDiv(w,h,t,l,p,bg){
        var div=document.createElement('div');
        div.style.width=w+'px';
        div.style.height=h+'px';
        div.style.position='absolute';
        div.style.top=t+'px';
        div.style.left=l+'px';
        div.style.padding=p+'px';
        div.style.border='1px solid #000';
        div.style.backgroundColor='#'+bg;
        document.getElementsByTagName('body')[0].appendChild(div);
    }

    As you can see, the above function takes a few incoming parameters, such as “width”, “height”, “top” and “left” coordinates, background color, and builds up a DIV element, by appending it to the document tree. Eventually, this function might be called as follows:

    createDiv(200,100,10,10,5,'0f0');

    Probably, you’ve used a similar function dozen of times, so I won’t stop on it for long. However, the interesting thing about it is that I’ll use its basic structure for creating DIV objects, instead of simply working with regular functions.

    The question that comes now is: how can a custom Div object be created? Well, take a closer look at the function listed below:

    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=display;
    }

    In simple terms, what I’ve done above is define a “Div” object by utilizing a similar syntax to the one used to define regular functions. After defining the “Div” function, which in this case is called a “constructor” function, I’ve specified the object properties, by utilizing the “this” keyword.

    For anyone who has worked with an object-based language like Java or a simpler one, such as PHP, the use of the “this” keyword should be pretty straightforward. If its meaning is a rather foreign concept to you, the “this” pointer in question is used to point to the current instance of the object being utilized. Bearing in mind this idea, you can spawn as many Div objects as needed, and each of them can hold a different value for the same property, because each object really acts as an independent data structure within the context of an application.

    Now, by returning to the definition for Div objects, notice the “display” property is defined as a method of the object. This condition is telling us that all Div objects also expose a “display” method. So, maybe you’re wondering…how do I tie this method to the object itself? The answer is simply by defining it as an ordinary function, like this:

    function display(){
        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);
    }

    Here, I’ve linked the above method to the constructor function for Div objects, so it uses all the properties declared within the constructor for displaying a DIV element on a web page. As you can see, the concept and the notation used above are quite simple to grasp, so I’ll instantiate a new Div object and insert it iinto the web document:

    var div=new Div(300,250,50,50,5,'f00');
    // display div
    div.display();

    The above snippet uses the “new” keyword to create a new “Div” object, by calling the corresponding constructor, (the “Div” function), and executing the block of instructions contained in it. After a “Div” object has been instantiated, its “display()” method is called, using the values assigned to its properties. In accordance with the parameters passed to the constructor, a red div element will be absolutely positioned on the web document, and its dimensions will be of 300px X 250px respectively.

    As a matter of fact, the above approximation for tying methods to objects looks unintuitive, because methods are declared outside the constructor, and sometimes it’s pretty hard to see the relationship between objects and their methods. That said, let’s look at an alternative syntax for coupling methods to objects inside the corresponding constructor.

    More JavaScript Articles
    More By Alejandro Gervasio


       · This firt tutorial introduces the core concepts for creating user-defined objects in...
       · I was suprissed to see that the wrong way is still used. The correct way to OO in...
       · Thank you for commenting on my JavaScript article.Actually, the method for...
       · Hi, I've been using objects in JavaScript for quite a long time and it was always...
       · Thank you so much for the positive comments, since they're very useful....
       · Maybe it's because it's IE, but when I copied and pasted the code:function...
       · Hello,Thank you for your comments on this article. Regarding your question, I've...
     

    JAVASCRIPT ARTICLES

    - 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
    - Assigning Background Colors Dynamically to Z...
    - Building Zebra Tables with CSS and JavaScript
    - JavaScript: Array Objects
    - A Closer Look at Smart Markers with Yahoo! M...
    - Using Polylines and Smart Markers with Yahoo...
    - Bulleted Menu of Links
    - Creating Click Loggers and Basic Markers wit...
    - Adding Pan Controls to Yahoo! Maps







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway