Last active
August 6, 2017 03:05
-
-
Save AlexKalinin/f2f5b23a0987aca9677c35e35f2ede36 to your computer and use it in GitHub Desktop.
Javascript Singleton Example
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
window.AuthApi = (function(){ | |
var instance; | |
function AuthApiObject(){ | |
uid = Math.random(); | |
return { | |
foo: function(){ | |
console.log('foo'); | |
}, | |
bar: function(){ | |
console.log('bar'); | |
}, | |
id: function(){ | |
return uid; | |
} | |
} | |
} | |
return { | |
getInstance: function(){ | |
if(!instance){ | |
instance = new AuthApiObject(); | |
} | |
return instance; | |
} | |
}; | |
})(); | |
AuthApi.getInstance().id(); | |
// 0.7436067988164723 | |
AuthApi.getInstance().id(); | |
// 0.7436067988164723 | |
AuthApi.getInstance().id(); | |
// 0.7436067988164723 | |
AuthApi.getInstance().id(); | |
// 0.7436067988164723 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//shorter version