Friday, March 14, 2014

declaring private variables in javascript

in the below function the variable age is called the private variable declaration, because we return the variable value as object, inside the function. and calling that function by assigning that function to person.
byusing that person we can access the object data inside the function.

   function abc() {

var age = 23;


return {

xyz:age

      }

}


var person = abc();
person.xyz   --->output is 123
person.age  ---->output is undefined

abc.xyz = 123; //this is called public variable declaration through function name
alert(abc.xyz); ---> output is 123

clear example:

<!DOCTYPE html>
<html>
<body>

<p id="intro">Hello World!</p>

<script>
 function abc() {

var age = 23;


return {

xyz:age

      }

}


var person = abc();
alert(person.xyz);
//alert(person.age);

abc.xyz = 123; //this is called public variable declation through function name
alert(abc.xyz);
</script>

</body>
</html>

No comments:

Post a Comment