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).
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
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.