Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Forked from sl4m/gist:166903
Created August 13, 2009 19:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcoglan/167422 to your computer and use it in GitHub Desktop.
Save jcoglan/167422 to your computer and use it in GitHub Desktop.
// If you return a value from the `initialize()` method, that value
// is returned when you instantiate the class using `new`.
// Here, we use this to make `singleton` a class that generates
// new classes. The singleton instance is protected by a closure.
JS.singleton = new JS.Class({
initialize: function(name, parent, methods) {
var instance = null;
return new JS.Class(name, parent, {
extend: {
getInstance: function() {
return instance = instance || new this();
}
},
initialize: function() {
if (instance) throw new Error('Cannot reinstantiate a singleton class');
try { this.callSuper() } catch (e) {}
},
include: methods
});
}
});
// test code
var A = new JS.Class("A", {
initialize: function(name) {
this.name = "Albert";
}
});
var B = new JS.singleton("B", A, {
display: function() {
console.log("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"
B.klass === JS.Class // -> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment