Created
August 13, 2009 01:21
-
-
Save sl4m/166903 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
// 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