Skip to content

Instantly share code, notes, and snippets.

@sl4m
Created August 13, 2009 01:21
Show Gist options
  • Save sl4m/166903 to your computer and use it in GitHub Desktop.
Save sl4m/166903 to your computer and use it in GitHub Desktop.
// insert in core.js
JS.singleton = function(name, parent, methods) {
var args = arguments;
return (function(args) {
// store instance and class in private variables
var instance = null;
var klass = new JS.Class(name, parent, methods);
return {
getInstance: function() {
if (instance) { return instance; }
return (instance = new klass());
}
};
})(args);
};
// test code
var A = new JS.Class("A", {
initialize: function(name) {
this.name = "Albert";
}
});
var B = new JS.singleton("B", A, {
display: function() {
Log.Message("My name is " + this.name);
}
});
var b = B.getInstance(); // runs A.initialize()
var b = B.getInstance(); // does not run A.initialize()
b.display(); // -> "My name is Albert"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment