-
-
Save joshski/1071935 to your computer and use it in GitHub Desktop.
Javascript patterns
This file contains hidden or 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 (Why isn't this code inside some module, is it just dangling?) | |
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, preferences) { | |
this.name = name; | |
this.shouldSaveChanges = preferences.isPersistent(); | |
}; | |
// Add instance functions to prototype | |
galleryConstructor.prototype.show = function () { | |
if (this.shouldSaveChanges) { | |
// depending on prefs but without the global access | |
} | |
}; | |
// Return constructor function | |
return galleryConstructor; | |
}(news, this)); | |
// Constructor function usage | |
var myGallery = new news.Gallery('My gallery', news.preferences); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment