Skip to content

Instantly share code, notes, and snippets.

@sourcec0de
Created May 8, 2014 18:57
Show Gist options
  • Save sourcec0de/fd59a5df3d44453e2f09 to your computer and use it in GitHub Desktop.
Save sourcec0de/fd59a5df3d44453e2f09 to your computer and use it in GitHub Desktop.
How to avoid global variables in Javascript - https://www.youtube.com/watch?v=hQVTIJBZook#t=1679
/**
* Avoid Global Variables
* ========================
* One easy way to avoid global variables in javascript
* is to use closures. This is a best practice that not only makes it
* so you only initialize your variable 1 time, but you keep your global namespace clear.
*/
var digit_name = function () {
var names = ['zero','one','two',
'three','four','five','six',
'seven','eight','nine'];
return function(n){
return names[n];
};
}();
alert(digit_name(1));
/**
* Model Pattern
* ========================
*/
var singleton = function () {
var privateVariable;
function privateFunction (x) {
// private variables
}
return {
firstMethod: function(a, b) {
},
secondMethod: function(c) {
}
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment