Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active August 29, 2015 14:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Williammer/9af8b88896ab7b83333d to your computer and use it in GitHub Desktop.
Save Williammer/9af8b88896ab7b83333d to your computer and use it in GitHub Desktop.
implement a singleton klass with redefine constructor pattern and IIFE.
// Constructor way
function SingletonKlass() {
var instance;
SingletonKlass = function SingletonKlass() {
return instance;
}
SingletonKlass.prototype = this;
instance = new SingletonKlass();
instance.constructor = SingletonKlass;
// properties.
instance.createdTime = 0;
instance.getRandNum = Math.random();
return instance;
}
// IIFE way
var SingletonKlass;
(function() {
var instance;
SingletonKlass = function SingletonKlass() {
if(instance){
return instance;
}
instance = this;
// properties.
instance.createdTime = 0;
instance.getRandNum = Math.random();
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment