HTML5 Zone is brought to you in partnership with:

Avi is a senior developer with a passion for Java technologies… http://www.aviyehuda.com/ Avi is a DZone MVB and is not an employee of DZone and has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

JavaScript encapsulation & the module pattern

01.15.2013
| 4550 views |
  • submit to reddit

 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

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

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
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

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

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



Published at DZone with permission of Avi Yehuda, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Daniel Quinn replied on Fri, 2013/08/02 - 12:25pm

This doesn't work, at least how I expected it to work. The 'private' variable x behaves as a private static variable for every instance of f1. My impression was you were trying to create a private instance of x for each object instantiated using f1.

Avi Yehuda replied on Fri, 2013/08/02 - 12:39pm in response to: Daniel Quinn

You are right, it does act as a static member, but it still counts as encapsulation, and that is what I was trying to achieve. But your point indeed needed to be said, thanks.

Daniel Quinn replied on Fri, 2013/08/02 - 1:00pm in response to: Avi Yehuda

No problem, I appreciate your example. Its a problem I've been trying to solve and you helped me come up with an answer(I think). Here's my solution, using the factory pattern, that encapsulates the object data, creates a unique, private instance per object, while still being efficient(memory).

var F1Factory = {
    newInstance: function(x_) {
        var x = x_;
    
        var Class = function() {};
        
        Class.prototype.getX = function () {
            return x;
        };
        return new Class();
    }
};

var i1 = F1Factory.newInstance(1);
alert(i1.x); // undefined
alert(i1.getX()); // 1

Avi Yehuda replied on Fri, 2013/08/02 - 3:39pm in response to: Daniel Quinn

Hi Daniel.

I don't think that your solution is memory efficient

Notice that the Class and getX() method are created on each instance that is created.

Daniel Quinn replied on Fri, 2013/08/02 - 8:54pm in response to: Avi Yehuda

Silly mistake, thanks for catching that. I guess the search continues...:)

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.