So let’s say I want to pass in an object containing settings to my class in JavaScript, but also provide default options, how would I do that easily? For example:
myClass = function(options){
var defaults = {
foo: 'foo',
bar: 'bar'
};
};
customOptions = {
bar: 'foobar'
};
myInstance = new myClass(customOptions);
So in this case, I would like for myInstance() to use foo='foo' since it was not specified by the user, and bar='foobar' as that was set by the user.
Now, I’ll be dealing with a bigger and more complex JSON object, obviously, and it seems inefficient and hard to maintain to check every property every time, so is there some way to combine these objects easily, overwriting as needed, with the user supplied properties always taking precedence?
You can check if the custom options object contains the properties you are looking for, and if not set default values.