Skip to content

Instantly share code, notes, and snippets.

@jcleveley-zz
Created June 15, 2011 10:44
Show Gist options
  • Save jcleveley-zz/1026868 to your computer and use it in GitHub Desktop.
Save jcleveley-zz/1026868 to your computer and use it in GitHub Desktop.
Javascript patterns
// namespace - single global variable for all news JS
var news = news || {};
// Example of a singleton as a revealing module
// When you only need one of something
news.preferences = (function (app, global) {
// Private variables
var persistent = true;
// Initialise Code
// Functions
var isPersistent = function () {
return persistent;
};
// Public interface
return {
isPersistent: isPersistent
};
}(news, this)); // <-- pass in app and global scope
// Singleton usage
news.preferences.isPersistent();
// Example of constructor function
// When you need multiple instances of something
news.Gallery = (function (app, global) {
// Constructor function
var galleryConstructor = function Gallery(name) {
this.name = name;
};
// Add instance functions to prototype
galleryConstructor.prototype.show = function () {
};
// Return constructor function
return galleryConstructor;
}(news, this));
// Constructor function usage
var myGallery = new news.Gallery('My gallery');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment