Private Variables

Description

JavaScript has no private members, but we can make a variable private by defining them inside a function.

Function arguments, local variables, and functions defined inside other functions are not accessible outside.


Consider the following:

function add(num1, num2){
   var sum = num1 + num2;
   return sum;
}

In this function, there are three private variables: num1, num2, and sum.

A closure inside a function would have access to these variables through its scope chain. In this way, we can create public methods that have access to private variables.

A privileged method is a public method that has access to private variables/functions.

Example

We can create private variables inside a constructor.


function MyObject(){/*from  ww  w .  j a v a  2s.  c om*/
    //private variables and functions
    var privateVariable = 10;

    function privateFunction(){
        return false;
    }

    //privileged methods
    this.publicMethod = function (){
        privateVariable++;
        return privateFunction();
    };
}

This pattern defines all private variables and functions inside the constructor. Then privileged methods can be created to access those private members.

Example 2

You can define private and privileged members to hide data that should not be changed directly, as in this example:


function Person(name){/*from  ww  w .j  av a 2s .c  om*/
   this.getName = function(){
      return name;
   };
   this.setName = function (value) {
      name = value;
   };
}
var person = new Person("XML");
console.log(person.getName());   
person.setName("CSS");
console.log(person.getName());   

The constructor in this code defines two privileged methods: getName() and setName(). Each method is accessible outside the constructor and accesses the private name variable.

Outside the Person constructor, there is no way to access name.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions