Similar to Oli's answer, I use an argument Object and an Object which defines the default values. With a little bit of sugar...
/**
* Updates an object's properties with other objects' properties.
*
* @param {Object} destination the object to be updated.
* @param {Object} [source] all further arguments will have their properties
* copied to the <code>destination</code> object in the
* order given.
*
* @return the <code>destination</code> object.
* @type Object
*/
function extendObject(destination)
{
for (var i = 1, l = arguments.length; i < l; i++)
{
var source = arguments[i];
for (var property in source)
{
if (source.hasOwnProperty(property))
{
destination[property] = source[property];
}
}
}
return destination;
}
...this can be made a bit nicer.
function Field(kwargs)
{
kwargs = extendObject({
required: true, widget: null, label: null, initial: null,
helpText: null, errorMessages: null
}, kwargs || {});
this.required = kwargs.required;
this.label = kwargs.label;
this.initial = kwargs.initial;
// ...and so on...
}
function CharField(kwargs)
{
kwargs = extendObject({
maxLength: null, minLength: null
}, kwargs || {});
this.maxLength = kwargs.maxLength;
this.minLength = kwargs.minLength;
Field.call(this, kwargs);
}
CharField.prototype = new Field();
What's nice about this method?
- You can omit as many arguments as you like - if you only want to override the value of one argument, you can just provide that argument, instead of having to explicitly pass
undefined
when, say there are 5 arguments and you only want to customise the last one, as you would have to do with some of the other methods suggested.
- When working with a constructor Function for an object which inherits from another, it's easy to accept any arguments which are required by the constructor of the Object you're inheriting from, as you don't have to name those arguments in your constructor signature, or even provide your own defaults (let the parent Object's constructor do that for you, as seen above when
CharField
calls Field
's constructor).
- Child objects in inheritance hierarchies can customise arguments for their parent constructor as they see fit, enforcing their own default values or ensuring that a certain value will always be used.