I am using a singleton pattern class in coffeescript, which is shown below recently. It works fine, but I don't know why this might be a singleton pattern. This might be a dumb question, but thanks for your answer.
#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 the code below is javascript which is created 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 for the definition of "singleton pattern" and how they are created at all, but the reason why the code above always returns the same instance instead of creating a new one.
source share