While recently coming back to clean up some Node.js module
code I was looking for a nicer way to handle configuration of an object besides
doing something like this to handle both configuration options and defaults.
var MyModule = function(opts){
this.foo = opts.foo || 1;
this.bar = opts.bar || 2;
// the list goes on
}
In my opinion this code is not really readable, and defaults are not as
obvious as I would like them to be. So I decided to let myself get inspired from
jQuery which provides a nice way to handle settings and defaults in plugins, via
$.extend(defaults, options) so my first
Idea was to simple create an extend function in node, but since I would have to
extend Object to make this as clean as possible I was looking for a way to
handle this natively, and this is where
Object.create
comes in handy.
Object.create allows creating of an object based on some prototype as well as
some default values, which is exactly what I was looking for. Do to the way
Object.create handles properties the options need to be prepared before merging
them in the configuration, which is finally bound to this.
var MyModule = function(opts){
// some default values
var defaults = { foo: 1, bar: 2 };
// prepare the options for Object.create
var options = {};
for(var i in opts){
options[i] = {
value: opts[i],
enumerable: true,
writeable: true,
configurable: true }
};
}
// let Object.create merge the options with the defaults
var config = Object.create(defaults, options);
// bind to this
for(var o in config){
this[o] = config[o];
}
}
Any suggestions for a different cleaner handling of configuration options are
highly welcome.
EDIT: Fixed extra level of nesting in options thanks to Sami Samhuri