Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Javascript module pattern with constructor with arguments

Javascript module pattern

As Douglas Crockford wrote on Javascript: the good parts, a module is a function or object that presents an interface but hides its state and implementation.

I used indeed the module pattern once I needed encapsulation, i.e. to have a class method that had a public interface but that hid implementation details.

In addition to encapsulation I needed a costructor with arguments, so I added it too in the following code, which implements the module pattern with a constructor.

function Module(name) {
	this.name = name;
} 

Module.prototype = (function() {
	var i = 0;

	function myPrivateFun() {
		console.log("private " + i++);
	}
	
	function myPublicFun() {
        myPrivateFun();
		console.log(this.name);
	}
	
	return {
		publicFun: myPublicFun
	};
	
})();

var m = new Module("john");
m.publicFun(); // private 0 John

The constructor is defined as it is usually done in Javascript.

The module pattern has been used in the prototype implementation, where we have

  • privateFun which is a private method, visible only from publicFun
  • publicFun which is a public method, externally visible
  • the return which returns an object whose members are externally visible, and so where we put public method

We have used in the code:

  • immediately invoked function expressions
  • closures

Immediately invoked function expressions

IIFE (immediately invoked function expressions), like

(function() {
 })();

make so that the function is immediately executed, and that the result is returned with the return we talked about above

Closures

Closures allow functions defined in a certain scope to continue to have access to the variables declared in that scope even when the outer function which defined that scope has terminated. In the example above we see how we access the variable i even when the outer function has ended its life cycle.

The post Javascript module pattern with constructor with arguments appeared first on Just Think.



This post first appeared on Just Think, please read the originial post: here

Share the post

Javascript module pattern with constructor with arguments

×

Subscribe to Just Think

Get updates delivered right to your inbox!

Thank you for your subscription

×