Introduction
In an object-oriented language like C# or Java, there are private and public members like variables and functions. If I declared a member of the class as private, then this is available inside that class. Only outside of the class it's not accessible. Javascript is object-oriented, so it has private and public members.
Below is the code for the private variable.
Note: Private variables are declared using the var keyword inside the object. This can access only private functions.
- function DisplayFullname(firstname,lastname)
- {
- // this are public fields
- this.FirstName=firstname;
- this.LastName=lastname;
- // this is Private variable which is accessible only inside of this constructor function.
- var fullname=this.FirstName+" "+this.Lastname;
- }
In the above code, fullname is a private variable and is not accessible outside of that function. It's accessible only inside of that function.
Below is the code for that private function which is accessible inside of the constructor function.
- function DisplayFullname(firstname,lastname)
- {
- // this are public fields
- this.FirstName=firstname;
- this.LastName=lastname;
- // this is Private variable which is accessible only inside of this constructor function.
- var fullname="";
- var getFullName=function()
- {
- fullname=this.FirstName+" "+this.LastName;
- return fullname;
- }
- }
Privileged Function
The function declared using this keyword is called a privileged function. In the below code, previlageFunction is an example of a privileged function.
- function DisplayFullname(firstname,lastname)
- {
- // this are public fields
- this.FirstName=firstname;
- this.LastName=lastname;
- // this is Private variable which is accessible only inside of this constructor function.
- var fullname="";
- var getFullName=function()
- {
- fullname=this.FirstName+" "+this.LastName;
- return fullname;
- }
- this.previlageFunction=function()
- {
- return getFullName();
- }
- }

Join the conversation! Your thoughts help the community grow.