HowTo: object orientated programming / OOP in Javascript (create a simple class)

 

Because of the increasing hype about AJAX and the “file-format” JSOPN, another subject in the field of web-developmen gets more and more interesting: Javascript-development.

All in all, in my opinion a little change is happening to web-development – we try to realize many things on the client.

I appreciate this change because, why should I communicate with the server while sorting a chart when the files are already on the client?

Exactly these are the types of assignments that are done by Javascript-Frameworks today. In Microsoft´s ASP.NET AJAX Extensions you will find a client-library as well. But there is a general question: How is it possible to encapsulate files in such a Framework? How is it possible to define own Javascript classes with methods?

 

Defining classes and methods in Javascript – Keyword “prototype”

Prototype is not only a keyword in the fields of Javascript Framework for defining methods, also in the world of JS.

But step by step now.

We create a very simple example: a rectangle. The attributes are width and height and we just want to know the area.

Step 1: defining the constructor including member

function Rectangle()
    {
        this.height;
        this.width;
    }

In fact, the constructor is a normal JS function because the keyword “class” doesn´t exist in JS. After that we tell them our two attributes “width” and “height” and as usual in OOP beginning with “this”.

Step 2: defining getter/setter

Of course it´s possible to pass the files directly to the constructor (“Rectangle(10, 5)”) but today we are going to use the getter/setter method where the “prototype” is important for:

 Rectangle.prototype.setHeight = function(value)
    {
            this.height = value;
    }
    Rectangle.prototype.getHeight = function()
    {
            return this.height;
    } 

We are going to “prototype” the rectangle and tell them, that we have a “setHeight” and a “getHeight” function and both have access to the attributes of the class with the keyword “this”.

Same thing for the other attribute of course.

Step 3: create Calc method

The method we need for the calculation of the area is as easy as we thought. “prototype” and reach the data via “this”:

Rectangle.prototype.calc = function()
    {
            var result = this.getWidth() * this.getHeight();
            return result;
    }    

Step 4: create objects and test them

In the simple demo-application (bottom left) we create the objects in a JS Function which is called in the onload.

function initApp()
    {
        var objectA = new Rectangle();
        objectA.setHeight(10);
        objectA.setWidth(2);

        var objectB = new Rectangle();
        objectB.setHeight(15);
        objectB.setWidth(3);

        alert(objectA.calc());
        alert(objectB.calc());
    }

Step 5: result

It works. (tested IE7 and FF2);

image

image

A view into firebug shows us the hierarchy:

image

Continuative links:

I choose this simple example because I only found difficult alternatives in the Internet till now. If you want to learn more about this subject please take a look on this website.

[Source Code + Demoapplication]

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

About the author

Written by Code Inside Team

Learn more about our team.

One Response

Comment on this post

Recent Posts

  • Automated Security Analyser for ASP.NET websites

    Evil Hackers are lurking everywhere and many Web-applications are delicately and share “too much” with the attacker. A quick (first!) overview offers the Tool “ASafaWeb”. All the website does is making a few requests and writing an Analyses including problem solving’s. There are no permanent disadvantages (bad requests/ DoS attacks and so on). Example: KnowYourStack.com ...

  • image1489-570x194.png
    „Sign in with Twitter“ for your own ASP.NET WebApp

      “Sign in with Twitter” is a popular practice to authenticate the users on your website. One advantage compared to an own registration is the lower inhibition for the user. But on the other hand Twitter doesn’t fess up with all the information’s and you will get into a kind of addiction. At the end ...

  • image1485-570x194_thumb.png
    CodePlex is going to be updated

      CodePlex the Microsoft Open Source Project Hosting Plattform hasn’t changed that much in the last few years and for a few times I thought Microsoft stopped the whole developing process. But now I found out that there is still life in the project. Maybe it is because of the success of GitHub or because ...

  • image1474_thumb.png
    What does Adobe in the flash-free web? Magazine-Style Layouts with CSS Regions!

      Adobe is well known for Photoshop and Flash but of course there is a lot more. According to the “Future Post” from Google Adobe declared one of their big subjects on a Blogpost. I’m talking about the W3C Working Draft to CSS Regions. Adobe cooperates with the WebKit Team and W3C on this. What ...

  • image1471-523x194.png
    HTML 5 Games, Tooling & 3D

      Game Developing is an interesting subject for all kind of software developer. But as a web developer without any Flash-skills there aren’t that much starting points. With HTML5 and the combination between Javascript, CSS3 and fast browsers there are the first “robust” HTML5 games. HTML5 games? Is this real? Neowin created a “Top 10” ...

Support us