Create Private Property in Javascript Object

In this lesson, we will see how to create private properties in Javascript object

Object with public property

I am creating constructor function to create object. I have used this.name=value statement inside the function. Property name is public here and you can access it from the outside of the function

You will get the following output because your name property is public
>Fanta

Object with private property

Now lets try to make the name property private
I am introducing var name=value instead of this

Now you will get the following output
>Undefined
Your name property is now private and you can not access it from the outside of the function. That is why you get Undefined

How to access private property

To access to the private property of an object you can use the following code

getName() is a prototype function which has access to the private name property

Leave a Reply

Your email address will not be published. Required fields are marked *