对象可选配置模式的核心是调用方只传需定制属性,其余用默认值;属性存在检查(in、hasOwnProperty、??等)用于判断是否显式提供配置项以决定是否覆盖默认值。

对象的可选配置模式,核心是让调用方只传入需要定制的属性,其余使用默认值。属性存在检查(in 操作符、hasOwnProperty、Object.prototype.hasOwnProperty.call 或可选链 + ??)就是判断某个配置项是否被显式提供,从而决定是否覆盖默认值。
用 in 检查属性是否存在(含继承)
in 操作符能检测对象自身或原型链上是否存在该属性,适合宽松场景——只要配置项被声明(哪怕值为 undefined),就视为“用户有意设置”。
例如:
const defaults = { timeout: 5000, retry: 3, log: false };
function request(url, options = {}) {
const config = {
timeout: 'timeout' in options ? options.timeout : defaults.timeout,
retry: 'retry' in options ? options.retry : defaults.retry,
log: 'log' in options ? options.log : defaults.log
};
// ...
}
这样调用时:request('/api', { timeout: 2000, log: undefined }) 会把 log 设为 undefined,而不是默认的 false。
用 hasOwnProperty 严格检查自有属性
如果只认用户直接写在配置对象上的属性(排除继承和 undefined 值的歧义),应使用 obj.hasOwnProperty(key) 或更安全的 Object.prototype.hasOwnProperty.call(obj, key)。
- 避免因原型上有同名属性导致误判
- 区分
{ log: undefined }和完全没写log
示例:
function createButton(props) {
const defaultProps = { size: 'medium', disabled: false, type: 'button' };
return {
size: Object.prototype.hasOwnProperty.call(props, 'size')
? props.size
: defaultProps.size,
disabled: Object.prototype.hasOwnProperty.call(props, 'disabled')
? props.disabled
: defaultProps.disabled,
type: props.type ?? defaultProps.type // 可选链+空值合并,简洁处理 null/undefined
};
}
结合解构与空值合并(??)简化写法
现代 JS 中,常用解构 + ?? 实现轻量可选配置,语义清晰且自动跳过 null 和 undefined:
function connectDB({ host = 'localhost', port = 5432, user, password } = {}) {
const config = {
host,
port,
user: user ?? 'admin',
password: password ?? 'guest'
};
// ...
}
注意:?? 不会触发对 0、false、'' 的覆盖,比 || 更准确;但无法区分 { user: null } 和 {} ——两者都会用默认值。
封装成通用合并工具函数
当多个地方需要类似逻辑,可抽离为复用函数,明确控制“覆盖策略”:
function applyOptions(defaults, options) {
const result = { ...defaults };
for (const key in options) {
if (Object.prototype.hasOwnProperty.call(options, key)) {
result[key] = options[key];
}
}
return result;
}
// 使用
const config = applyOptions({ retries: 2, timeout: 3000 }, userConfig);
这种写法天然支持浅合并,不修改原对象,也兼容 undefined、null 等显式赋值。











