Skip to content

Instantly share code, notes, and snippets.

@lgmkr
Forked from jcleveley-zz/patterns.js
Created August 21, 2012 12:43
Show Gist options
  • Select an option

  • Save lgmkr/3415082 to your computer and use it in GitHub Desktop.

Select an option

Save lgmkr/3415082 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