Created
June 15, 2011 10:44
-
-
Save jcleveley-zz/1026868 to your computer and use it in GitHub Desktop.
Javascript patterns
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
// 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