Tech
Forums
Jobs
Books
Events
Interviews
Live
More
Learn
Training
Career
Members
Videos
News
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Public and Private Methods in JavaScript
WhatsApp
Yogesh Jaiswal
4y
14.9k
0
0
100
Article
PublicPrivateMethods.zip
Public Members can be accessed anywhere using the "." notation.
Private Members can only be accessed within a constructor and public method.
Public methods and variables are declared using the "this" keyword like "this.variableName".
A Public method is accessed using a constructor; this technique is usually used to initialize public instance variables.
var objPublicPrivateClassg = new PublicPrivateClass();
Code
/*Comment
<CodeItem type="Method">Class Name</CodeItem>
<summary>Define the Class name as a function</summary>
<params>
</params>
<return></return>
Comment*/
function
PublicPrivateClass() {
//PublicMethods
this
.publicMethods = {
/*Comment
<CodeItem type="Method">InitializePageControlEvents</CodeItem>
<summary>Initialize the control</summary>
<params>
</params>
<return></return>
Comment*/
InitializePageControlEvents:
function
() {
privateMethods.PrivateTestMethod();
}
};
// Private Methods
privateMethods = {
/*Comment
<CodeItem type="Method">PrivateTestMethod</CodeItem>
<summary>Show the alert Message</summary>
<params>
</params>
<return></return>
Comment*/
PrivateTestMethod:
function
() {
alert(
"Calling Private Method."
);
},
PrivateTestMethod2:
function
() {
alert(
"PrivateTestMethod2"
);
}
};
}
HTML Code
Calling a Public Method:
<script type=
"text/javascript"
>
function
CallMethod() {
try
{
var
objPublicPrivateClassg =
new
PublicPrivateClass();
//InitializePageControlEvents is Public method
objPublicPrivateClassg.publicMethods.InitializePageControlEvents();
}
catch
(err) {
alert(err.message);
}
}
</script>
HTML Code
Calling a Public Method:
<script type=
"text/javascript"
>
function
CallMethod() {
try
{
var
objPublicPrivateClassg =
new
PublicPrivateClass();
//InitializePageControlEvents is Public method
objPublicPrivateClassg.publicMethods.InitializePageControlEvents();
}
catch
(err) {
alert(err.message);
}
}
</script>
Output
<script type=
"text/javascript"
>
function
CallMethod() {
try
{
var
objPublicPrivateClassg =
new
PublicPrivateClass();
//InitializePageControlEvents is Private method
objPublicPrivateClassg.privateMethods.PrivateTestMethod();
}
catch
(err) {
alert(err.message);
}
}
</script>
Output
Methods in JavaScript
Private Methods in JavaScript
Public Methods
Public Methods in JavaScript
Up Next
Ebook Download
View all
Frontend Developer Interview Questions and Answers
Read by 941 people
Download Now!
Learn
View all
Membership not found