Created
March 14, 2013 13:06
-
-
Save ChenReuven/5161139 to your computer and use it in GitHub Desktop.
JS : Structuring JavaScript Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** NameSpacing **/ | |
var myNS = myNS || {}; | |
/** Prototype Pattern **/ | |
var MyModule = function(){ | |
// private members | |
this.a = 0; | |
} | |
MyModule.proptotype = { | |
// public members | |
myFunction1 : function(){ | |
}, | |
myFunction2 : function(){ | |
} | |
}; | |
// Invoke Prototype Pattern | |
var myModuleObject = new MyModule(); | |
myModuleObject.myFunction1(); | |
/** Module Pattern **/ | |
myNS.MyModulePattern = function(){ | |
//private members | |
var a=5, | |
b=3, | |
c=5, | |
myFunction = function(){ | |
}; | |
//public members | |
return { | |
myFunction2 : function(){ | |
// Your Code Goes Here... | |
}, | |
myFunction3 : function(a,b){ | |
// your Code Goes Here... | |
}; | |
}; | |
}; | |
// Invoke Module Pattern | |
// Way 1 | |
var myModulePattern = new myModulePattern(); | |
myModulePattern.myFunction1(); | |
// Way 2 | |
MyModulePattern.myFunction1(); | |
/** RevealingModulePattern **/ | |
myNS.MyRevealingModule = function(){ | |
// private members | |
var a=5, | |
b=4, | |
myFunction1 = function(){ | |
// Your Code Goes Here... | |
}, | |
myFunction2 = function(){ | |
// Your Code Goes Here... | |
}, | |
myFunction3 = function(){ | |
// Your Code Goes Here... | |
}; | |
// public members | |
return{ | |
myFunction1 : myFunction1, | |
myFunction2 : myFunction2, | |
myFunction3 : myFunction3 | |
}; | |
}(); // Notic to () - Self Invoke! | |
// Invoke MyRevealingModule | |
myNS.MyRevealingModule.myFunction1(); | |
/** RevealingPrototypePattern **/ | |
myNS.myRevealingPrototypeModule = function(a, b, c){ | |
// private members | |
this.a = a, | |
this.b = b; | |
this.c = c; | |
}; | |
myNS.myRevealingPrototypeModule.prototype = function(){ | |
// private members | |
var myFunction1 = function(){ | |
// Your Code Goes Here... | |
}, | |
myFunction2 = function(){ | |
// Your Code Goes Here... | |
}, | |
myFunction3 = function(){ | |
// Your Code Goes Here... | |
}; | |
// public members | |
return { | |
myFunction1 : myFunction1, | |
myFunction2 : myFunction2, | |
myFunction3 : myFunction3 | |
}; | |
}; | |
// Invoke myRevealingPrototypeModule | |
// Way 1 | |
var myObject = new myNS.myRevealingPrototypeModule(1,2,4); | |
myObject.myFunction1(); | |
// Way 2 | |
myNS.myRevealingPrototypeModule.myFunction1(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment