Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Last active December 18, 2015 00:09
Show Gist options
  • Save bloodyowl/5695070 to your computer and use it in GitHub Desktop.
Save bloodyowl/5695070 to your computer and use it in GitHub Desktop.
singleton pattern
var mySingleton = (function(){
var instance = null
function K(){
if(!instance || this !== instance) throw "Constructor is a singleton"
return this
}
K.prototype.foo = function(){}
K.prototype.bar = function(){}
K.prototype.bar = function(){}
return function(){
if(!instance) instance = K.call(Object.create(Constructor.prototype))
return instance
}
})()
function singleton(object){
var instance = null
return function(){
if(!instance) instance = Object.create(object)
return instance
}
}
@piecioshka
Copy link

Nice code, but in my opinion, word Constructor is not usable to this situation :) this is only my opinon, at first I say wtf is this :D

@bloodyowl
Copy link
Author

@piecioshka True, that's because I decided to use Object.create afterwards. I renamed it to a generic K.

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