I have a JavaScript class I would like to supply with default values using an object. I only want the default values to be part of the class if user input is not otherwise supplied for some of the values. However, I am not sure how to implement this. Here is my class:
// Class definition, properties, and methods
class iTunesClient {
constructor(options) {
this.term = options.terms;
this.country = options.country;
this.media = options.media;
this.entity = options.entity;
this.attribute = options.attribute;
this.callback = options.callback;
this.limit = options.limit;
this.lang = options.lang;
this.version = options.version;
this.explicit = options.explicit;
this.url = options.url;
}
}
// Default values defined according to iTunes API
const defaults = {
terms: 'default',
country: 'US',
media: 'all',
entity: '',
attribute: '',
callback: '',
limit: 50,
lang: 'en-us',
version: 2,
explicit: 'yes',
url: '',
};
A typical way to do this is to use Object.assign()
to merge passed-in values with default values:
// Class definition, properties, and methods
class iTunesClient {
constructor(options) {
// Default values defined according to iTunes API
const defaults = {
terms: 'default',
country: 'US',
media: 'all',
entity: '',
attribute: '',
callback: '',
limit: 50,
lang: 'en-us',
version: 2,
explicit: 'yes',
url: '',
};
let opts = Object.assign({}, defaults, options);
this.term = opts.terms;
this.country = opts.country;
this.media = opts.media;
this.entity = opts.entity;
this.attribute = opts.attribute;
this.callback = opts.callback;
this.limit = opts.limit;
this.lang = opts.lang;
this.version = opts.version;
this.explicit = opts.explicit;
this.url = opts.url;
}
}
To explain how Object.assign()
works here:
{}
as a target (an empty object)Of course, if your instance property names are the same as the ones in your options object, you could do this in a more DRY fashion like this:
// Class definition, properties, and methods
class iTunesClient {
constructor(options) {
// Default values defined according to iTunes API
const defaults = {
terms: 'default',
country: 'US',
media: 'all',
entity: '',
attribute: '',
callback: '',
limit: 50,
lang: 'en-us',
version: 2,
explicit: 'yes',
url: '',
};
let opts = Object.assign({}, defaults, options);
// assign options to instance data (using only property names contained
// in defaults object to avoid copying properties we don't want)
Object.keys(defaults).forEach(prop => {
this[prop] = opts[prop];
});
}
}