-
Notifications
You must be signed in to change notification settings - Fork 38
Modules and Singletons
Although augment
is primarily an inheritance library, yet it can also be used to create modules and singleton instances. On the Getting Started page I documented the type signature of the augment
function:
augment :: Function | Object // A base class constructor or prototype
-> Function // The definition of the new class or prototype
-> ... // A bunch of other optional arguments
-> Function | Object // Return a new class or prototype
The augment
function returns either a function or an object. How does it know what to return? If you define a constructor
property on the prototype then it returns the constructor. Otherwise it returns the prototype. For example:
var MyModule = augment(Object, function ($) {
var secret = true;
this.version = "public";
this.doSomething = function () {
// use jQuery to do something interesting
};
}, jQuery);
if (MyModule.version === "1.0.0") {
alert("First major release.");
}
MyModule.doSomething();
Since I did not define this.constructor
, the augment
function returned an object inheriting from Object
instead of a function. This is similar to using the module pattern. Extra parameters given to augment
are given to the module body. This is similar to an import.
Modules are essentially singleton instances and indeed singleton instances can be implemented using the module pattern. However, most singletons are initialized on-demand. The augment
function allows you to write those kind of singletons too:
var MySingleton = augment(Object, function () {
this.version = "static";
this.getInstance = function (options) {
var instance = augment(this, init, options);
this.getInstance = function () {
return instance;
};
};
function init(options) {
// do some customization using options
var secret = options.secret;
this.public = options.public;
// do some resource intensive initializations
// like opening database connections
this.doSomething = function () {
// do something interesting
};
}
});
if (MySingleton.version === "1.0.0") {
alert("First major release.");
}
var mySingletonInstance = MySingleton.getInstance({
secret: false,
public: true
});
mySingletonInstance.doSomething();
console.log(MySingleton.getInstance() === mySingletonInstance); // true
console.log(mySingleton.isPrototypeOf(mySingletonInstance)); // true
Creating modules and singleton instances using augment
is fairly straightforward. Nevertheless, singletons are usually a sign of bad code design and should be used sparingly.