-
-
Save jcoglan/167422 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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