WTH is Encapsulating Javascript?

Over the weekend, I’ve been doing javascripting and some one messaged me on how to write an encapsulating javascript functions which is a common practice in web development nowadays. Especially when we involved in mobile where memory and processor is critical

I remember around 8 years ago when, javascript was just a simple procedural language used for web development then it evolved into DHTML which we can use to make cool effects. Later, comes AJAX and wonderful js frameworks we had today.


Today this script language evolved into some kind of magical development language of wonders – you can even write a full mobile to desktop app using this scripting language with the help of cross compilers.

Because of that, developing a javascript application can lead to complex scripting due to huge number of variables and objects you control.

Therefore for best practice sake,

  1. You need to keep your javascript functions in main webpage as minimal as possible and js files must be as human readable as possible. e.g. <script src=”calculate.js”></script> should at least have calculate related functions in it like  “calculate.sum( myNumberList );” so that, is easy to use calculate.js like an util file.
  2. Don’t pollute the global scope! – A complex javascript script will have alot of variable flowing everywhere thus polluting the global scope and making it easier to read. (this means, we don’t overuse var VariableName everywhere in our js file – put in an encapsulated js instead) To control that, we use encapsulated function. An Encapsulated function are  more than a function, less than a traditional OOP class but better than nothing 🙂 .
  3. There’s several ways I found can achieve this but, I’m gonna list this one first because is one of my favorites.
Method one, encapsulating js using namespace and self-triggering function.

What is a self-triggering function?, Self -triggering function is a function construct which fires straightaway. We normally use that for “container” – to contain variables, and related functions.

Here is how to write a self triggering function,

(function(){
	alert('fired immediately');
})();

Let’s write a chained self triggering function. Follow the code below.

var trigger = function(){
       alert('chained function');
}();
 
//try calling it using
trigger();
// and compare with
trigger;

Noticed, the behaviour of trigger, is no longer regarded as function in browser. In-fact, if you use trigger(); you will get an error in firebug. Notice also that, when you just call trigger without brackets, and yet it fires the function. This is how we do our namespace in encapsulating js.

Let’s work on other namespace – this time with proper function, namespace are used to clearly define and separate our javascript so that, same function names and variables don’t get mixed up. It’s like writing a class with methods all encapsulated within.

var calc = function(){
    return {};
}

The code above simply creates a function that returns nothing. We normally use this as our namespace starter/definer. Then, we proceed further with writing a specific function / method like construct e.g. calc.sum.

Note calc.sum is undefined, if you do not declare a namespace starter/definer which is a chained self-triggering function in memory that returns nothing.

//Secondary Namespace calc.sum - wrapped using self triggering function
calc.sum = function(){
	/* private variables only to calc.sum see how variables are kept within */
	var value1 = 0;
	var value2 = 0;  
 
	// private method to calc.sum
	function calc(){
	var sum = parseInt(value1) + parseInt(value2);
	    return sum;
	}
 
	// public functions
	return {
	    init: function(external_value1, external_value2){
	         this.setValue1(external_value1);
	         this.setValue2(external_value2);
	    },
 
	    setValue1: function(val){
	        value1 = val;
	    },
 
	    setValue2: function(val){
	        value2 = val;
	    },
 
	    getSum: function(){
	       // calling an internal private function
               // (requires no "this.")
		return calc();
	    }
	}
}();

Now, we have a “class util” like javascript, and everything is kept within…isn’t that neat?

To use, we simply need to init it.

//init calc.sum which requires two integer,
calc.sum.init(10,30);
alert(calc.sum.getSum());
// should return you 40

Today’s tutorial in HTML : encapsulatedJS (551 downloads)

 

Comments

comments