This is how I normally do it, with some sort of extend
method, and a .defaults = {}
object, jQuery's works in this case.
function SomeObject(data) {
$.extend(this, SomeObject.defaults, data);
}
SomeObject.defaults = {
field1: '',
field2: ''
};
var newObject = new SomeObject({ field1: 'field1' });
console.log(newObject);
// > { field1: 'field1', field2: '' }
You could say that we have defined a default mixin for SomeObject
, since we are $.extend
ing this
. This way we can let $.extend
handle the null
/undefined
checks.
As far as handling errors in the object you can initialize your defaults to null
and throw new Error()
when something is not passed in.
function SomeObject(data) {
$.extend(this, SomeObject.defaults, data);
if (this.field1 == null) {
throw new Error('SomeObject: field1 is required');
}
}
SomeObject.defaults = {
field1: null,
field2: null
};
var newObject = new SomeObject({ field2: 'field2' });
// > Error: SomeObject: field1 is required
Two great articles about throwing errors