Coming from an old-school way of handling my defaults, I am trying to wrap my head around how to allow default values within an object literal for a constructor, while calling the constructor with a partial object literal. Note: I am still not a fan of "class" syntax for constructors, but I intend to use it, so please indulge me while I learn!
Code speaks louder than words. Here was my first attempt:
class ProxyManager {
constructor(
proxy = {
proxyID: 12345,
proxyHost: '',
proxyPort: 8080,
proxySSL: false,
proxyPath: ''
}
) {
this.proxy = proxy;
}
getProxy() {
return this.proxy;
}
}
const foo = new ProxyManager();
foo.getProxy(); // returns the full default object defined in the constructor
const bar = new ProxyManager({proxyID: 67890});
foo.getProxy(); // returns {proxyID: 67890}
None of this is a surprise; you can see right from the syntax that as long as something is passed in as the first paramater, it becomes "proxy". So, while I wasn't expecting it to work, it was my starting point.
Out of familiarity, I fell back to an older-school way of doing it, which is something like this:
class ProxyManager {
constructor(proxy) {
this.proxy = proxy || {};
const defaults = {
proxyID: 12345,
proxyHost: '',
proxyPort: 8080,
proxySSL: false,
proxyPath: ''
}
// swap in more thorough sanity-check if needed
if (Object.prototype.toString.call(this.proxy) === '[object Object]') {
this.proxy = Object.assign(defaults, this.proxy)
}
}
getProxy() {
return this.proxy;
}
}
const foo = new ProxyManager();
foo.getProxy(); // returns the full default object defined in the constructor
const bar = new ProxyManager({proxyID: 67890, proxyPort: 16500});
foo.getProxy(); // returns full object with updated proxyID and proxyPort
It works, and I guess I could move on... but I am interested to see if there is a pattern I'm missing. I did some searching, and kept coming up short.