JavaScript Notes – 1
Posted: August 19th, 2011 | Author: nramakrishnan | Filed under: technical | Tags: javascript, technical | Comments OffMy notes on JavaScript Patterns. This is just a part of the patterns covered by Addy Osmani and those covered by Stoyan Stefanov
**Disclaimer**: The code examples below are modified examples from JavaScript Patterns
Namespaces
Using global variables and functions in JavaScript can lead to smashing of variables as the code base grows. So a simple way of handling namespaces is
var NxJ = {};
NxJ.property1 = "Name is Nadu";
NxJ.method1 = function(){console.log("name is bond, james bond");}
// if you want to add modules
NxJ.modules.module1 = {};
NxJ.modules.module1.data = {"a":1,"b":2};
var moduleToBeUsed = NxJ.namespace("NxJ.module1.module2.module_n");
The variable names keep getting larger and larger. A way to handle this is to create a function called namespace, that can parse the module name and return only that module with all the methods. Useful when you are using big libraries like YUI (they have different modules for DOM, Events etc)
Private properties, Module and Revealing Module
By default everything is public
var myObj = {
myName : “Nadu”;
getName = function(){
return myName;
}
};
console.log(myObj.myName); // accessible
So a way of fixing this is
myObj = ( function(){
// a var before myName - makes it private
var myName = “Nadu, the Private”;
return: // yes return an object
{
getName = function(){
return myName;
}
};
}());
console.log(myObj.myName); // inaccessible now
console.log(myObj.getName()); // this is the right way to get it
Points to note -
- Immediate function call – so what value does myObj get?
- var before myName makes it private because of closure
- getName is a privileged function
Lets add namespaces now,
var NxJ = {};
NxJ.coolModule = ( function(){
// a var before myName - makes it private
var myName = “Nadu, the Private”;
var yourName = “Someone else”;
return:
{
getName = function(){
return myName;
},
setName = function(n){
myName = n;
}
};
}());
So that’s the Module pattern!
Since we have reached alive till here, we will jump to the Revealing module pattern, which is nothing but a simple extension of the Module pattern.
In the Revealing module pattern, you define all the properties as private in the object and then return only those that you want to be made public
var NxJ = {};
NxJ.coolModule = ( function(){
// a var before myName - makes it private
var myName = “Nadu, the Private”;
var yourName = “Someone else”;
var getName = function(){return(myName);};
var setName = function(n){ myName = n;}
return:
{
getName: getName,
getTheAwesomeName: getName // sort of an alias!
};
}());
console.log(NxJ.coolModule.getName());
console.log(NxJ.coolModule.getAwesomeName()); // this works too
There are 2 advantages of this pattern, one is that it’s a little more cleaner than the Module pattern and two you can have these aliases. One can create a JavaScript API and then just return all that is public.
Be careful!
var NxJ = {};
NxJ.coolModule = ( function(){
// a var before myName - makes it private
var student = {"name":"Nadu", "age":"18-till-i-die"};
var getStudent = function(){ return student; }
return {
getStudent: getStudent
};
}());
var stud = NxJ.coolModule.getStudent();
console.log(NxJ.coolModule.student); // not possible
console.log(stud.name); // says Nadu
stud.name = "Narayanan Ramakrishnan"; // trying to modify it
var stud2 = NxJ.coolModule.getStudent();
console.log(stud2.name); // prints Narayanan Ramakrishnan - Hey WTF ?
This is because for arrays and objects, JavaScript returns the reference, so its accessible to anyone who has the reference. So one way of handling this is to return a new object that has properties that the caller is interested in. Called the Principle of Least Authority which states that you should never give more than intended. One way of doing this in the example above is, instead of giving the caller everything, you can break it down into functions getName(), getAge(). There is another approach using a general purpose cloning function, but that will be covered later.
More notes to follow in another post.
Further reading
A beautiful explanation of Module Pattern by Twitter engineer Ben Cherry
Signing off treat – www.jsfiddle.net