Skip to content

Instantly share code, notes, and snippets.

@robpataki
Created July 18, 2015 22:10
Show Gist options
  • Save robpataki/68d16324708ce3887818 to your computer and use it in GitHub Desktop.
Save robpataki/68d16324708ce3887818 to your computer and use it in GitHub Desktop.
Very simple implementation of the singleton pattern in requirejs
define(
[],
function() {
'use strict';
var instance = null;
function Singie() {
if(!!!instance){
this.initialize();
instance = this;
}
window.SINGIE = instance; // Good to have reference on window
return instance;
};
Singie.prototype = {
initialize: function() {
this.hello = 'Hello'
this.world = 'World'
this.sayHello = function sayHello() {
return this.hello + ' ' + this.world;
}
}
};
return Singie;
}
);
@robpataki
Copy link
Author

To use the singleton instance:

_this.singie = new Singie();
console.log(_this.singie.sayHello());

// Should pop 'Hello World' in the console

To test if it is indeed a sole singleton instance:

_this.singieClone = new Singie();
console.log(_this.singie === _this.singieClone);

// Should be true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment