JavaScript is a fascinating language. The lack of built-in OOP concepts and chaotic structure (from the first sight), allows a big degree of flexibility that allows programmers to mimic almost any OOP pattern and achieve common OOP practices.
The absence of “public” and “private” scopes can be substituted with closure functions and namespaces.
Here’s a small example of a closure function that emulates public and private scope:
var NM = {}; //basic namespace
NM = (function(){
var _foo = 2; //private variable within namespace
//private method accessible within namespace only
var _add = function(b) {
_foo += b;
};
//public scope is an anonymous object returned
return {
addition : function(a) {
_add(a); //calling private method within public
}
};
})(NM);
NM.addition(2); //works
NM._add(3); //doesn't workIt allows to clean up code base, dealing with heavy load of client-side programming. Program-wise it becomes easier to separate code into sub-namespaces and distinguish all programming logic between its areas of implementation. Futhermore, keeping code clean and structured this way allows avoiding various bugs and compile JS in lighter versions with Closure JS Compiler or any other.
