Private variables and methods are those that accessed only within an object. Private variables are defined with var keyword. They are manipulated by private functions and privileged methods. Usage of private variables and methods eliminates global variables, and encourages module pattern. It promotes information hiding and is effective way of encapsulating data.

Private functions are defined inside a constructor or with var functionName = function(){…..}. They are accessed by privileged methods only. 

Privileged methods are declared with this.methodName = function(){…..} and can be accessed outside the object. Through closures they can access private variables and private functions. There are two ways of creating privileged methods:

Creating privileged methods inside a constructor

Privileged methods can be created inside constructor as in the example below:

Example of privileged methods inside a constructor

Creating privileged methods through module patterns

Another way to create privileged methods is through module patterns combined with singleton pattern. Singletons are created using object literal notations as below:

Example of privileged methods created through module patterns

var singleton={
    variable: value,
    method: function(){
        //method code
    }
};

Combining module pattern with singleton are done in an anonymous function. Firstly the private variables and methods are defined. Then privileged methods and properties that are public are defined as object literals. This pattern is widely used when there is initialization required after creation of the components as well as access to private variables. The method exposes public methods to manipulate private variables.

Example of privileged methods created through module patterns with initialization

 

›› go to examples ››