Singleton.js
JavaScript Singletons made easy.
Installation
$ npm install singleton.js
var singleton = ;
Browser
ES5 browser (>= IE9) required.
API
singleton(Ctor)
arguments
Ctor
Optional. Function constructor.
returns
- Singleton function constructor.
- Returns initial instance for all subsequent instantiations.
new
is optional.- Inherits from passed function constructor.
- Will have own properties of passed function constructor.
var Modal = ;Modalprototype = { /****/ } { /****/ }; === // => true instanceof Modal // => true
{ thispriority = priority;}Modalprototype { /****/ };Modalprototype { /****/ }; // Create a singleton from an existing function constructorvar Alert = ;10; === // => true// `new` is optional === // => true instanceof Alert // => true instanceof Modal // => truepriority // => 103priority // => 10
// Define singleton's constructorvar Printer = ;Printerprototype { /****/ }; 'Office Printer';name // => 'Office Printer''Chuck'name // => 'Office Printer'
Example with Backbone.js Collections
var Movie = BackboneModel; var Movies = ; // Alternatively// var Movies = singleton(Backbone.Collection);// Movies.prototype.model = Movie; === // => true ; length // => 2 // Static/Own properties are maintainedvar BMovies = Movies; instanceof Movies // => true instanceof BackboneCollection // => true