I use singleton pattern class in coffeescript which shown below recently. It works perfectly but I don't know why this could be a singleton pattern. This might be a stupid question but thanks for your answering.
#coffeescript
class BaseClass
class Singleton
singleton = new Singleton()
BaseClass = -> singleton
a = new BaseClass()
a.name = "John"
console.log a.name # "John"
b = new BaseClass()
b.name = "Lisa"
console.log b.name # "Lisa"
console.log a.name # "Lisa"
and code below is javascript which is produced by the code above
var BaseClass, a, b;
BaseClass = (function() {
var Singleton, singleton;
function BaseClass() {}
Singleton = (function() {
function Singleton() {}
return Singleton;
})();
singleton = new Singleton();
BaseClass = function() {
return singleton;
};
return BaseClass;
})();
a = new BaseClass();
a.name = "John";
console.log(a.name);
b = new BaseClass();
b.name = "Lisa";
console.log(b.name);
console.log(a.name);
EDITED : I am not asking the definition of 'singleton pattern' nor how they are generally created but the reason why the code above always returns the same instance instead of creating new one.