Create Private Property in Javascript Object

Last Updated: September 19, 2017

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

function Product(value){
    this.name=value
}

var product= new Product("Fanta")
console.log(product.name)

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

function Product(value){
    var name=value
}

var product= new Product("Fanta")
console.log(product.name)

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

function Product(value){
   var name=value
}

Product.prototype.getName=function(){
    return name
}

var product= new Product("Fanta")
console.log(product.getName())

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