Created
May 9, 2009 02:08
-
-
Save nw/109094 to your computer and use it in GitHub Desktop.
Class Initializers (Singleton)
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
Class.Initializers = {}; | |
Class.initializer = function(obj){ return this._initializer_ = obj; } | |
Class.Mutators.initialize = function(initialize){ | |
if(!this._initializer_) return initialize; // quick exit | |
return function(){ | |
this._init_ = initialize; | |
for (var modifier in Class.Initializers) { | |
if (!this[modifier]) continue; | |
this[modifier] = Class.Initializers[modifier].call(this, this[modifier]); | |
} | |
delete this.constructor['_initializer_']; | |
return this._init_.apply(this, arguments); | |
}; | |
}; | |
// We set the mutator so we can set a flag for the heavy 'initialize' mutator | |
Class.Mutators.Singleton = Class.initializer; | |
Class.Initializers.Singleton = function(){ | |
var init = this._init_; | |
this._init_ = function(){ | |
var instance = init.apply(this, arguments) || this; | |
this.constructor.prototype.initialize = function(){ | |
return instance; | |
}; | |
return instance; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment