Click here to Skip to main content
Click here to Skip to main content

OOP in JavaScript.

, 14 Sep 2004
Rate this:
Please Sign up or sign in to vote.
OOP aspects of JavaScript programming language.

Introduction

The article by Sergey Zavadski introduces the object model of the JavaScript programming language and demonstrates common practices in the OOP (object oriented programming) with JavaScript.

Simplicity of JavaScript.

JavaScript is proven to be one of the simplest programming languages to learn and use. A minor snippet of the code (in fact one string) performs various actions like creating of windows or changing the text in the status bar. The flexibility, short learning curve, and the fact that JavaScript is not a “strongly typed” language explains the extreme popularity of JavaScript among the web masters community which selected this language as the language of choice to provide static HTML pages with dynamic attractive content.

The powerful tool

However, in spite of its visible simplicity, the JavaScript, when following the DOM specifications, is quite an advanced and powerful tool providing all the required facilities for the creation of complex solutions (client side) such as menus, trees, grids etc. These possibilities are actually reflecting JavaScript’s power when it comes to the layers manipulations. Not the last reason for this power is the OOP structure of the JavaScript programming language which was planned and implemented as an object oriented language!

Object model

The JavaScript object is the entity with the properties that can be either other objects or variables. For example, we have Country_Italy object. We can assign the values to the properties of this object like this:

Country_Italy.Name=”Italy”;
Country_Italy.Capital=”Rome”;
Country_Italy.Area=301000;

However, the ‘Country_Italy’ object itself can be the property of another object:

Europe.MostBeautifulCountry= Country_Italy;

JavaScript comes with a library of built-in objects like Window, Math, String and many others. But what makes the language really flexible is the ability of creating custom objects. There are two possible methods for making custom objects in JavaScript. First one is using the direct initialization. The code in this case may look like this:

Country={Name:”France”,Capital:”Paris”,Government:{President:”Jacques Chirac”}};

We have created the Country object with ‘Name’, ‘Capital’ and ‘Government’ properties, and ‘Government’ property is an object with its own list of properties. We’ve also initialized these properties with initial values. All of this is done in one single string. The following construction creates and initializes the empty object:

Country={};

Another way to create objects in JavaScript is defining the special function constructor for the object and initialization of the object with the ‘new’ operator. For example:

function Country(Name,Capital,Population){
     this.Name=Name;
     this.Capital=Capital;
     this.Population=Population;
}

The ‘Country’ function is the constructor function. Now, to create the object using this defined constructor, we use the new operator:

Country_Italy=new Country(“Italy”,”Rome”,301000);

Just like in the previous example, the property can be the object itself:

function Government(President){
     this.President=President;
}
 
function Country(Name,Capital,Government){
     this.Name=Name;
     this.Capital=Capital;
     this.Government=Government;
}
Government_France=new Government(“Jacques Chirac”);
Country_France=new Country(“France”,”Paris”,Government_France);

Another advantage of the OOP fully implemented in JavaScript is that an object can have methods (not only properties). The methods are the functions described within an object scope that usually operate with the object’s properties. The methods are described much like the properties:

function describeCountry(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
           alert(desc);
}

In the above definition, this operator provides an access to the object the described method belongs to.

Country_Italy.describeCountry=describeCountry;

The construction below fully repeats the above one:

Country_Italy.describeCountry=function(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
     alert(desc);
}

The construction:

Country_Italy.describeCountry();

calls the ‘describeCountry’ method of the ‘Country_Italy’ object.

Prototypes based object oriented language

Unlike some other popular OO languages (Java, C++) whose object model is based on classes, the object model of JavaScript is based on prototypes. The main difference between those two approaches is that in a prototype based language, there’s no difference between the class and the class instance entities – you only deal with objects.

The prototype (can be viewed as a template that defines the way initial object’s property values are assigned) is any object declared with the prototype operator. This object can be the parent of any newly created object and this is how JavaScript supports inheritance – an important OOP language characteristic. Let’s see our Country object:

function Country(Name,Capital,Population){
      this.Name=Name;
      this.Capital=Capital;
      this.Population=Population;
}

Now, let’s declare ‘Cn’ - the ‘Country’ object prototype:

Cn=Country.prototype;

Cn.describeCountry=function(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
           alert(desc);
}

Now, we can call the ‘describeCountry’ method in any ‘Country’ descendant with only two strings of code:

Country_Italy=new Country(“Italy”,”Rome”,301000);
Country_Italy.describeCountry();

Using this approach, we can define in the prototype any number of methods and properties. Defining methods and properties in the prototype rather then defining them directly for each object gives many advantages:

  • You don’t have to define all required methods or properties every time the object is designed. You define all the necessary methods and properties in the prototype and then all you have to do is to create the object.
  • Makes your code more secure since you can keep all object definitions in a separate file.
  • Makes your code easier to read.

Inheritance

JavaScript also supports the inheritance mechanism that is the corner-stone of OOP.

To show the easiness of JavaScript inheritance mechanism, let’s review two already defined objects of ours: ‘Country’ and ‘Government’, and one new object ‘Parliament’.

Constructor functions for these objects will look like these:

function Country(Name,Capital,Population){
     this.Name=Name;
           this.Capital=Capital;
     this.Population=Population;
}
 
function Government(President){
     this.President=President;
}
 
function Parliament(Speaker){
     this.Speaker=Speaker;
}

Take a look at the ‘Country’ object prototype.

Cn=Country.prototype;
 
Cn.describeCountry=function(){
           var desc=”Name: ”+this.Name+” Capital: ”+
this.Capital+” Population: “+this.Population;
     alert(desc);
}

The following construction defines ‘Country’ as ‘Government’ prototype (‘Government’ inherits from ‘Country’):

Government.prototype=new Country("France","Paris",59330000);

When ‘Government’ object is created, it inherits all the ‘Country’ methods and properties. In other words, although ‘describeCountry()’ method is not defined for ‘Government’ object, it is available since ‘Country’ object is defined as ‘Government’ prototype.

Government_France=new Government("Jacques Chirac");
Government_France.describeCountry();

New methods can also be defined for the ‘Government_France’ object:

Government_France.describeGovernment=function(){
             alert(“President: ”+this.President);
}

Let’s complete the ‘Parliament’ object definitions.

Parliament.prototype=new Country("France","Paris",59330000);
 
Pn=Parliament.prototype;
Pn.describeParliament=function(){
     alert("Speaker: "+this.Speaker);
}

Parliament_France=new Parliament("Jean-Louis Debre");

As you can see, prototypes can also be modified for the inherited objects.

The above examples demonstrate elegance of the JavaScript OOP model which enables this easy to learn language to perform a variety of complex tasks for the real life programming.

Real life example

This very OOP approach was used in our company when we developed the CodeThat.Com’s set of web controls. For example, the ‘CodeThatCalendar’ is nothing but an object declared as:

 function CodeThatCalendar(def) {
     this.def = def;
     this.links = {};
     this.styles = {};
     this.hideifr = true;
           
     if (typeof(this.def.img_path)!="undefined") {
         if (this.def.img_path.lastIndexOf("\/")!=this.def.img_path.length-1)
             this.def.img_path=this.def.img_path+"\/";           
     }
             
     if (typeof(this.def.template_path)!="undefined") {
         if (this.def.template_path.lastIndexOf("/")!=
                       this.def.template_path.length-1) 
             this.def.template_path=this.def.template_path+"/";             
         if (this.def.template_path.indexOf("\/")!=0) 
             if (typeof(this.def.img_path)!="undefined" && 
                        this.def.img_path.indexOf("\/")!=0) {
                 s=this.def.template_path;
                   a=s.split("/");
                 a.length=a.length-1;
                 t="";
                 for (i=0; i<a.length; i++){
                     t=t+"../";
                 }
                 this.img_path=t+this.def.img_path;      
                 } 
         }
     };
 
var CTc = CodeThatCalendar.prototype;
 
CTc.hide = function()
     {
     …
     }
 
CTc.create = function(d,ctl) {
           …
    }

Various methods of the control work with the layers giving the control a fancy look and feel and enabling users to perform various actions the calendar is supposed to do. For example, the below function sets the value of the HTML form control to the date the user has selected. This is performed each time the user clicks the calendar date.

function CodeThatSetDay(c,f,d,m,y,i,ifr) {
     var doc;
     var w = window.opener||this.parent;
 
     if(w&&!i)
           doc = w.document;
     else
           doc = document;
     var e = CodeThatFind(doc,c);
     if(Def(e))
     {
           e.value=CodeThatDateFormat(f,d,m,y);
           if(e.fireEvent) e.fireEvent("onchange");
           else {
            if(e.onchange) e.onchange();   
           }
     }
 
     if(w&&!i)                            
     {
 
           if(Def(w) && Def(ifr))
           {
                var iframe = CodeThatFind(doc,ifr);
                if(Def(iframe))
                     iframe.style.visibility = 'hidden';
                if(ua.opera6)
                {
                     var d = CodeThatFind(doc,"calendar_div");
                     if(Def(d))
                     d.style.visibility='hidden';
                }
           }
           else
           {
                window.close();
           }
     }
};

(The examples of CodeThatCalendar functions are not fully functional. They are listed here for illustrative purposes). As you can see, JavaScript is indeed a powerful and user friendly programming language with many abilities which help to create really complex and interesting solutions. Since the DOM model is supported by majority of modern browsers, you can be sure your solution will be accessible for the majority of users. Of course, there’s much more to learn in JavaScript: events, DOM, layers, and cross-browser portability is also not always that transparent but this is for another story or... several stories.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

aakaab
Web Developer
Ukraine Ukraine
No Biography provided

Comments and Discussions

 
GeneralJSOOP Library Pinmemberweerstra7-Jun-06 3:48 
QuestionHow can i make arrays using OOP in javaascript? PinmemberRafael - .net not mcp27-Sep-04 15:29 
AnswerRe: How can i make arrays using OOP in javaascript? Pinmembervolkan.ozcelik5-Oct-05 3:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 14 Sep 2004
Article Copyright 2004 by aakaab
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid