Skip to content

aviyehuda.com

Menu
  • Open Source
  • Android
  • Java
  • Others
  • Contact Me
  • About Me
Menu

JavaScript encapsulation & the module pattern

Posted on 12/01/2013

Encapsulation is one of the key features of object oriented programming languages.
In languages like Java, it is very straight forward concept to implement.

Since I know JavaScript is considered an OO language, I decided to try to understand once and for all how to implement encapsulation in JavaScript correctly.

Let’s say we have a function with one private field and one public field:

function f1() {
	var x=3; //private	
	this.y=4; //public
}

//alert(x); // error - x is undefined
//alert(y);// error - y is undefined
alert(f1.x); //alert undefined
alert(f1.y); //alert undefined
//alert(f1().x); //error - f1() does not return an object with property x
//alert(f1().y); //error - f1() does not return an object with property y

Try It

The fields are of course undefined since we need to call f1() in order for them to have values.

Now let’s create an object from that function:

var i1 = new f1();

//alert(x); // error 
//alert(y);// error 
alert(i1.x);//alert undefined since it is private
alert(i1.y); //alert 4

Try It

After instancing, x and y both have values, but of course, only y is public.

Now lets encapsulate field x.

function f1() {
	var x=3; //private	
	this.y=4; //public

	this.getX = function(){
		return x;
	}
}

var i1 = new f1();

//alert(x); //error
alert(i1.x); //alert undefined
alert(i1.getX()); //alert 3

Try It

This is the most basic encapsulation and it works.
But this approach has a problem, f1() is in fact a kind of constructor. Whenever an instance will be created than the getter method will also be created.
This approach is not the preferred way to create methods in JavaScript.

The preferred approach in JavaScript is to create the methods attached to the prototype. In this way they will only be created once.

var f1 = function(){
	var x=3; //private	
	this.y=4; //public
}

f1.prototype.getY = function(){
	return y;
}

/* error
f1.prototype.getX = function(){
	return x; //x is not a public field
}
*/

But this approach also has a problem, we cannot use it for private fields.

Let’s consider using a module

f1 = (function (){
	var x=3;

	var module = function (){
		this.getX = function(){
			return x;
		}
	}

	return module;
})();

var i1 = new f1();
alert(i1.x); //undefined
alert(i1.getX()); //3

Try It

There is a function which creates a module with the getter.
But here we have the same problem as the first example, getX() is created for every instance.

The solution is in fact a combination of the previous 2 examples:

f1 = (function (){
	var x=3;

	var module = function (){}
	
	module.prototype.getX = function(){
		return x;
	}

	return module;
})();

var i1 = new f1();

//alert(x); undefined
alert(f1.x); //undefined
alert(i1.getX()); //3

Try It

Here you have a strict encapsulation which is also efficient in memory.

5 thoughts on “JavaScript encapsulation & the module pattern”

  1. Andreas says:
    26/03/2013 at 14:10

    Note that while x may be private, it’s shared for all instances. Might be useful for private constants, but not for variables.

    Reply
  2. Ryan says:
    26/03/2013 at 18:57

    I don’t believe your final solution is any more memory efficient than the 3rd example you gave.

    You are creating a new object/prototype every time you instantiate a new f1(), thus eliminating the benefit of prototyping all together.

    Reply
    1. Avi says:
      26/03/2013 at 22:11

      Hi Ryan,
      I believe that you havent looked at the last solution carefully enough, because what you say is simply not true.

      First of all, of course every time someone instantiates a new f1(), a new object is creates, that is simply the meaning of instantiation.

      What that makes this solution more efficient is the fact that the getter method – getX() is created only once, and not on every instantiation. Not only I do not eliminate the use of prototyping I am actually using it for my benefit.
      Perhaps I should have been more clear regarding that.

      BTW, If you still don’t believe me that the getter method is created only once, please take a look at this example which I have created especially for you:
      http://jsfiddle.net/aviyehuda/a6x4N/

      Reply
      1. Erik says:
        04/08/2013 at 17:30

        That fiddle helped a lot to clarify.. you should consider rewriting your post to make this more clear

        Reply
  3. vikash kumar says:
    30/08/2014 at 06:59

    very nice post.. thank you so much. dude!

    Reply

Leave a Reply Cancel reply

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


About Me

REFCARD – Code Gems for Android Developers

Categories

  • Android
  • AWS
  • AWS EMR
  • bluetooth
  • Chrome extension
  • ClientSide
  • Clover
  • Coding Coventions
  • Data Lake
  • General
  • GreaseMonkey
  • Hacks
  • hibernate
  • hibernate validator
  • HTML5
  • HtmlUnit
  • Image Manipulation
  • Java
  • Java Technologies
  • JavaScript
  • Java_Mail
  • JEE/Network
  • Job searching
  • Open Source
  • Pivot
  • projects
  • Pure Java
  • Python
  • software
  • Spark
  • Trivia
  • Web development

Archives

  • November 2023 (1)
  • October 2023 (1)
  • March 2022 (1)
  • January 2022 (1)
  • January 2021 (1)
  • December 2018 (1)
  • August 2018 (1)
  • October 2013 (1)
  • March 2013 (1)
  • January 2013 (2)
  • July 2012 (1)
  • April 2012 (1)
  • March 2012 (1)
  • December 2011 (1)
  • July 2011 (1)
  • June 2011 (1)
  • May 2011 (2)
  • January 2011 (1)
  • December 2010 (1)
  • November 2010 (3)
  • October 2010 (4)
  • July 2010 (1)
  • April 2010 (2)
  • March 2010 (1)
  • February 2010 (2)
  • January 2010 (5)
  • December 2009 (10)
  • September 2009 (1)
 RSS Feed
074638315b5fcb316afdf0dec4f3a8d7-332
©2023 aviyehuda.com | Design: Newspaperly WordPress Theme