我来自一种老式的处理默认值的方法,我正在尝试思考如何在构造函数的对象文字中允许默认值,同时使用部分对象文字调用构造函数。注意:我仍然不喜欢构造函数的"class“语法,但我打算使用它,所以请在我学习的时候纵容我!
代码胜于雄辩。这是我的第一次尝试:
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}这并不奇怪;您可以从语法中看到,只要将某些内容作为第一个参数传入,它就会变成“代理”。所以,虽然我没料到它会起作用,但它是我的起点。
出于熟悉,我又回到了一种老式的方法,它是这样的:
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它起作用了,我想我可以继续前进...但我感兴趣的是,我是否遗漏了一种模式。我做了一些搜索,但总是找不到答案。
发布于 2020-09-29 01:46:08
根据评论,原始问题中的选项#2并不是一个糟糕的解决方案。这可能比下面的更好。但为了全面起见,我们得出了以下结论:
class ProxyManager {
constructor(
{
proxyID = 12345,
proxyHost = '',
proxyPort = 8080,
proxySSL = false,
proxyPath = ''
} = {}
) {
this.proxy = {
proxyID,
proxyHost,
proxyPort,
proxySSL,
proxyPath
}
}
getProxy() {
return this.proxy;
}
}对于像我这样的老一辈JS用户来说,这可能更难摸索,而且为了最终的结果,这肯定是不必要的重复。但它符合我最初的问题标准,所以这里将其作为答案。附带的好处是,您不必执行一堆健全的检查来确保默认设置有效。如果使用无效的参数调用构造函数(例如,传入一个简单的字符串或int),则仅应用默认值。另一方面,这也是缺点...不会出现错误使用构造函数的警告。
https://stackoverflow.com/questions/64096931
复制相似问题