Last active
August 27, 2015 20:59
-
-
Save kebman/97293fc381c1521db895 to your computer and use it in GitHub Desktop.
How to easily create a namespace in JavaScript to avoid polluting global space
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
// Check if the namespace 'KEB' is available globally | |
if (!KEB) { | |
// If it is, then assign an object to the 'KEB' variable, and you have your namespace! | |
var KEB = {}; | |
} | |
// Write a variable (attribute) to the namespace | |
KEB.name = "KEB"; | |
// Write a function (method) to the namespace | |
KEB.sayHello = function() { | |
console.log("Hello "+KEB.name); | |
} | |
// Run the function from the namespace | |
KEB.sayHello(); | |
// Now wasn't that easy? :D | |
// You can of course also work directly with the keys and values of the namespace object |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment