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).
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:
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
Wow!!! What's that?
We just made JavaScript functions behave like a class; now we can simply use them as:
- 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.