Skip to content

Instantly share code, notes, and snippets.

@kebman
Last active August 27, 2015 20:59
Show Gist options
  • Save kebman/97293fc381c1521db895 to your computer and use it in GitHub Desktop.
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
// 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