Reader Level:
ARTICLE

Implement Object Oriented Programming in JavaScript

On August 28, 2012 Articles | JavaScript
In this article we will discuss how to implement encapsulation in JavaScript to achieve reusability.
  • 2
  • 0
  • 4643
 

In this article we will discuss how to implement encapsulation in JavaScript to achieve reusability.

All of us know JavaScript has nothing like classes and inheritance.

As an ASP.Net developer, JavaScript plays a very important role in our activities, but without OOP it becomes cumbersome and less efficient.

But there is a way by which we can create JavaScript objects that behave like classes.

Scenario

Let's discuss a small scenario.

Consider we have a web form which contains a group of Pair elements (Textbox and button).

TextBoxButtonJavaScript.jpg

When the button is clicked for the first time the corresponding textbox color changes to something else and when clicked again returns to normal.

Simple Solution

In the form, handle the click event for each as follows:

FormOOPJavaScript.jpg

You can see here, much of the code is repeating.

Imagine the situation when we will have a group of say 10 pairs.

Disadvantages

  • Code management is difficult.
  • Very difficult to extend the functionality as any change requires changes in all blocks.
  • As the group increases the size increases in the same extent resulting in a performance penalty.
  • Testing is difficult since we will not be sure whether a block is working properly even when others work great.

Good solution

SolutionOOPJavaScript.jpg


Wow!!! What's that?

We just made JavaScript functions behave like a class; now we can simply use them as:

ClassOOPJavaScript.jpg

  • We have only a single copy of the actual logic so code management is easy.
  • Easily extend to more functionality.
  • Even when the number of groups increase the size of the code increases only a little.
  • Logic is working for one group => Logic will work for all groups.

OK that's it for the day; we just saw how we can implement OOP methodology in JavaScript programming

Download the source code attached and don't forget to share your comments here.

Thank you.
 

Sukesh Marla

I am asp.net developer with over 4 years experience,Proficient in Object Oriented Programming and jQuery.Achievements - MCPD with asp.net 3.5 and MCTS with SQL Server 2008.Hobbies - Blogging (www.suke...

Personal Blog: http://sukesh-marla.com
  • 72rank
  • 585K readers
  • 1times
COMMENT USING

Trending up