Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Implement Object Oriented Programming in JavaScript
WhatsApp
Sukesh Marla
4y
11.6k
0
2
100
Article
ImplementOOPinJavaScript.rar
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).
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 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
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 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.
encapsulation in JavaScript
JavaScript
JavaScript objects
OOP
Up Next
Ebook Download
View all
Voice of a Developer: JavaScript From Scratch
Read by 11k people
Download Now!
Learn
View all
Just Compile LLP
Just Compile is an IT based firm based out of Mumbai. Application Development, Staffing, Training
Membership not found