Encapsulation In JavaScript

Introduction :
Encapsulation is an important feature in object oriented programing (OOP). It is also very important to any developers, that they can secure their technology from others. A class is a template or prototype for each object instances made to the class design. The class specifies the properties and methods that objects can work with. Data secrecy is the ability of objects to shield variables from external access. It is a useful consequence of the encapsulation principle. This permits validity checking at run time. Access to other variables can be allowed but with tight control on how it is done. Methods can also be completely hidden from external use.

1. With the help of encapsulation an object can place both private and public under a same name.
2. With the help of encapsulation developers can protect sensitive information from others.

In this article we will see how we can use encapsulation in JavaScript. We can’t apply encapsulation directly in JavaScript. But through some methods like
1. Using singletons
2. Using module patterns.

Encapsulation in JavaScript using variables:

We can recreate encapsulation in JavaScript. In JavaScript we will use variables , not objects. Because an object can store data in one of two ways: as a property or as a variable. Object properties are created using the “this.” prefix. The name that follows the dot will identify a new property to add to the object’s properties collection. Variables, on the other hand, are created using the “var” keyword. It is subject to the rules of variable scoping. Private functions and privileged methods, like private variables and public properties, are instantiated with each new object created. At first we will see to these methods and then we will understand an example.

Using singletons:
The following code is creating one singleton object.

Var num = { 
    add: function()
        return this.x + this.y;

Using module patterns.:
In the following set of codes we are creating a module pattern where we define local variables inside a function and invoke it. The variables stay inside the function’s scope and return an object containing methods. This method is unable to work in case of inheritance.

Var  num = (function(){ 
Var x=0,y=0; // local variables.
	------Some functions---
} )(); 

Introducing a function named closure:
Unlike other languages, we can’t easily create public or private members in javascript. To create private members, we can get help from Closures.
In the previous code snippet we have used a type of function called closure, below is an example:

var num = (function(){function(){}})();

In this code we can see that we have used a pair of parenthesis after closing the function.
Closures are functions that refer to independent variables. Accessing variables outside of your immediate lexical scope creates a closure. As objects let us associate data with methods, likewise a closure let us associate data with functions in js. We can use this function in web development, because in web js is event based coding where we call a function in response of an event triggered by the user.
In a simple word we can say that closures are nothing but an inner function that has access to the outer (enclosing) function’s variables—scope chain.
Let us see a basic example implementing encapsulation with the help of closure.

Var stack = {};

  function( num )
    Var data = [];

    num.push = function( data )
        data.push( data );

    num.pop = function()
        return data.pop();
} )( stack ); //using closure

stack.push( 'value' );

Now let us continue with encapsulation.
Now we have an idea about closure and it’s uses. Now, implementing encapsulation through javascript would be much easier for us now. We can use a function that contains the private data and functions, and then return a limited set of public functions that can interact with the private data.
We can also invoke encapsulation in javascript by a different method. By creating a class to define our constructor, it’s methods and it’s properties. We are going to learn how to use this technique in following code snippets.

var rectangle = new Class({
     _width: 0, //creating private properties using underscore '_' , to let class understand
    _height: 0, //creating private properties.
     init: function(width, height) { 
        this.width = width;
        this.height = height;
     info: function() {
        return 'Width: ' + this.width +
                ',\nheight: ' + this.height +
                ',\narea: ' + this.calcarea();
     _calcarea: function() {
        return this.width * this.height;    }
var foo = new foo(100, 100);
foo.info(); //result

In the above example we have created a class named rectangle using

var rectangle = new Class({

Inside this class we have assigned two properties and made them private by using underscore ‘_’ . In the code, init: function(width, height) { we are using closure and encapsulating the rest of the methods in the function.

In this article we have learned to use encapsulation in javascript. We have seen many approaches for achieving javascript. Though the latest version of javascript Spider Monkey 1.8.5 doesn’t support encapsulation directly. But we still can achieve encapsulation in js with above technologies.
If you find this article helpful, you can connect us in Google+ and Twitter.

Enter your email address:Delivered by FeedBurner

1 thought on “Encapsulation In JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *