What is the simplest/cleanest way to implement singleton pattern in JavaScript?
How about this way, just insure the class can not new again.
By this, you can use the instanceof
op, also, you can use the prototype chain to inherit the class,it's a regular class, but can not new it,if yuu want to get the instance just use getInstance
function CA()
{
if(CA.instance)
{
throw new Error('can not new this class');
}else{
CA.instance = this;
}
}
/**
* @protected
* @static
* @type {CA}
*/
CA.instance = null;
/** @static */
CA.getInstance = function()
{
return CA.instance;
}
CA.prototype =
/** @lends CA#*/
{
func: function(){console.log('the func');}
}
// initilize the instance
new CA();
// test here
var c = CA.getInstance()
c.func();
console.assert(c instanceof CA)
// this will failed
var b = new CA();
If you don't want to expose the instance
member, just put it into a closure.