Skip to content

Instantly share code, notes, and snippets.

@AlexKalinin
Last active August 6, 2017 03:05
Show Gist options
  • Save AlexKalinin/f2f5b23a0987aca9677c35e35f2ede36 to your computer and use it in GitHub Desktop.
Save AlexKalinin/f2f5b23a0987aca9677c35e35f2ede36 to your computer and use it in GitHub Desktop.
Javascript Singleton Example
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
@AlexKalinin
Copy link
Author

//shorter version

window.AuthApi = (function(){
  var uid = Math.random();

  return {
    foo: function(){
      console.log('foo');
    },
    bar: function(){
      console.log('foo');
    },
    id: function(){
      return uid;
    }
  }
})();

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