Created
May 8, 2014 18:57
-
-
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
This file contains 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
/** | |
* 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