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){
          get : function(i){
               return array[i];

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}

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 1Part 2


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: