Closure in javascript Part 3

Using closure to hide collections

Here is a way to hide an array in closure

var objectContainer =  function(){
     var array = [];
     return {
          push : function(xVal,yVal){
               array.push({x:xVal,y:yVal});
               },//push
          get : function(i){
               return array[i];
               }//get
          };
     }();

We have an objectContainer object that has a push and get methods. Push method adds a new coordinate to array and get returns an object. In this example our array is safe because it is hidden. However, our objects in array are not. Getter method is returning real object that is stored in our array. So we can do unintended changes on that object. Can we make that part safe too? The answer is yes you can.In order to to that, you should change returned object’s get method with the following

 get :  function(i){
      var value = array[i]
      return {
           getX:function(){return value.x},
           getY:function(){return value.y}
           };
      }//get

As you see, we are also hiding our object under closure of get method. As a result, it will always be safe. We can now put any validation in our returned object. Our array structure is now indestructible.

Part 1 - Part 2

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: