Javascript does not have access modifier to be precise like other programming languages say Java.So How can we make a variable private.Let us see.
Consider following code snippet
//Immediately invoked function expression
let Person = (function()
{
let _age=0;
return {
firstName:"sangram",
lastName:"desai",
get age()
{
return _age;
},
set age(val)
{
_age = val
}
};
})()
//printing all accessible properties of object
for(let prop in Person)
{
console.log(prop);
}
console.log(Person.firstName)
console.log(Person.lastName)
//public properties
Person.age = 40;
console.log(Person.age)
//private variable
console.log(Person._age)
Output:
firstName
lastName
age
sangram
desai
40
undefined
Here _age is defined outside to make it private property.firstName & lastName are public properties of Person object.we defined age property using getter & setter syntax to access private property _age
We have printed all accessible properties of Person Object which happens to be
firstName
lastName
age
note _age is not there.
Then we try to directly print _age as follows
console.log(Person._age)
It comes out as undefined.
No comments:
Post a Comment