Implement Object Oriented Programming in JavaScript

Introduction

 
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 that 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 to 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 increases 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.


Similar Articles
Just Compile LLP
Just Compile is an IT based firm based out of Mumbai. Application Development, Staffing, Training