I am doing a small JavaScript module with an object of defaults options, it looks like this:
var myModule = function() {
// Define option defaults
var defaults = {
foo: 'bar',
fooObject: {
option1: [],
option2:true,
option3: false,
}
}
// Create options by extending defaults with the passed in arugments
if (arguments[0] && typeof arguments[0] === "object") {
this.options = extendDefaults(defaults, arguments[0]);
}
}
so when I call my module like that
var moduleInstance = new myModule({
foo: 'some value',
fooObject: {
option1: [1, 2, 3]
}
});
moduleInstance.options.foo; //will retrurn an array [1, 2, 3]
but
moduleInstance.options.fooObject; //will only contain option1
I understand why as option2 and option3 are not defined when creating the object, but i can't wrap my head around how to solve this. All the snippets that I found where using jQuery on another framework.
edit:
sorry the extendDefault() was missing here it is:
function extendDefaults(source, properties) {
var property;
for (property in properties) {
if (properties.hasOwnProperty(property)) {
source[property] = properties[property];
}
}
return source;
}
Edit: possible work around
i ended up doing it like this http://jsfiddle.net/optionsit/sgmme5dy/
in the loop that check for hasOwnProperty
I put that if statement
if(typeof properties[property] === 'object' && typeof properties[property].nodeType === 'undefined' )
so I can check if the value is an object but not a DOM element (as I am passing some DOM element in the top level values as well)
if it is a JavaScript object I iterate trough it's children to see if they are set in the arguments and replace them only if they are.
It may not be very pretty but it works for my use case, please feel free to comment if you have a better option I will accept a prettier answer.
Thanks for your help