Skip to content

Instantly share code, notes, and snippets.

@riversun
Created April 18, 2017 09:02
Show Gist options
  • Save riversun/a449dd2d4262958d30b846855c859d75 to your computer and use it in GitHub Desktop.
Save riversun/a449dd2d4262958d30b846855c859d75 to your computer and use it in GitHub Desktop.
Singleton class for JS(ES5 style)
//namespace[begin]****************************
var mypackage;
if (mypackage === undefined) {
mypackage = {};
}
//namespace[end]****************************
mypackage.MyClass =
(function () {
'use strict';
/**
* @constructor
*/
function MyClass() {
this._privateName = 0;
}
/**
* Method
* @returns {number}
*/
MyClass.prototype.getName = function () {
var me = this;
return me._privateName;
};
//Normal Class
//return MyClass;
var _instance;
//Singleton Class
return {
getInstance: function () {
if (!_instance) {
_instance = new MyClass();
}
return _instance;
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment