Use the properties of the user-supplied object if it exists, otherwise use the default values
So, let's say I want to pass an object containing settings to my class in JavaScript, but also provide default parameters, how would I do this 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 to myInstance()
use foo='foo'
as it was not specified by the user, and bar='foobar'
as it was specified by the user.
Now I will be dealing with a larger and more complex JSON object, obviously and seems inefficient and difficult to maintain to check each property every time, so is there a way to easily combine these objects, rewrite as needed, with the same user-supplied property priority?
source to share
You can check if the custom options object contains the properties you are looking for and if no defaults are provided.
myClass = function(options) {
this.foo = options.foo || 'foo';
this.bar = options.bar || 'bar';
};
customOptions = {
bar: 'foobar'
};
myInstance = new myClass(customOptions);
source to share
You can do something like this:
var MyClass = function (options) {
var defaults = {foo: 1, bar: 2};
for (var option in defaults) {
this[option] = options[option] || defaults[option];
}
}
var customOptions = { bar: 5};
var c = new MyClass(customOptions);
Basically, configurable parameters are looped through and any missing parameters are added with their default values. In this case, c.foo = 1
and c.bar = 5
. The script is available at http://jsfiddle.net/2Ve3M/ .
source to share
You can try something like this:
myClass = function(options){
var myOptions = {
foo: options.foo || 'foo',
bar: options.bar || 'bar'
};
};
If you are using jQuery you can also look at http://api.jquery.com/jQuery.extend/
source to share