Singletons
A singleton class is one which can only ever have one instance. The concept is
more useful in Java, where you cannot create an object without first creating
a class. JavaScript allows objects without classes (indeed, it has no classes,
only objects) but using Singleton
lets you create custom objects from
existing jsclass
classes, allowing you to inherit methods, include modules
and use method()
et al.
// In the browser JS.require('JS.Singleton', function(Singleton) { ... }); // In CommonJS var Singleton = require('jsclass/src/core').Singleton;
To create a singleton:
var Camel = new Singleton(Animal, { fillHumpsWithWater: function() { ... } }); // You can call instance methods... Camel.speak('the desert'); // from Animal Camel.fillHumpsWithWater(); var s = Camel.method('speak'); s('drinking'); Camel.klass.superclass // -> Animal
Singleton
just creates a class with the arguments you give it, immediately
instantiates this new class and returns the instance. You can access the class
through Camel.klass
as shown above.