Skip to content

Instantly share code, notes, and snippets.

@mrmikee
Last active January 31, 2016 22:21
Show Gist options
  • Save mrmikee/4e48688521b71010027c to your computer and use it in GitHub Desktop.
Save mrmikee/4e48688521b71010027c to your computer and use it in GitHub Desktop.
JavaScript NameSpacing Example
//Here is their example showing how to declare private & public properties and functions. Everything is done as a self-executing anonymous function.
(function( skillet, $, undefined ) {
//Private Property
var isHot = true;
//Public Property
skillet.ingredient = "Bacon Strips";
//Public Method
skillet.fry = function() {
var oliveOil;
addItem( "\t\n Butter \n\t" );
addItem( oliveOil );
console.log( "Frying " + skillet.ingredient );
};
//Private Method
function addItem( item ) {
if ( item !== undefined ) {
console.log( "Adding " + $.trim(item) );
}
}
}( window.skillet = window.skillet || {}, jQuery ));
//So if you want to access one of the public members you would just go skillet.fry() or skillet.ingredients.
//=====================================================
//What's really cool is that you can now extend the namespace using the exact same syntax.
//Adding new Functionality to the skillet
(function( skillet, $, undefined ) {
//Private Property
var amountOfGrease = "1 Cup";
//Public Method
skillet.toString = function() {
console.log( skillet.quantity + " " +
skillet.ingredient + " & " +
amountOfGrease + " of Grease" );
console.log( isHot ? "Hot" : "Cold" );
};
}( window.skillet = window.skillet || {}, jQuery ));
//example found here: http://stackoverflow.com/questions/881515/how-do-i-declare-a-namespace-in-javascript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment