具名参数与默认参数的函数封装

对象参数结构方式(ES6+) - 推荐

// 定义函数
function fetchData({
  url = '/api/data',
  method = 'GET',
  timeout = 5000,
  retry = 3
} = {}) {
  console.log(`Fetching from ${url} with ${method}`);
  console.log(`Timeout: ${timeout}ms, Retry: ${retry} times`);
  
  // 实际请求逻辑...
}

// 调用方式
fetchData(); // 使用所有默认值
fetchData({ url: '/api/users' }); // 只覆盖url
fetchData({ 
  method: 'POST', 
  timeout: 10000 
}); // 覆盖部分参数,不按顺序

传统参数对象方式(ES5及以下)

function fetchData(options) {
  // 设置默认值
  const settings = {
    url: '/api/data',
    method: 'GET',
    timeout: 5000,
    retry: 3,
    ...options // 覆盖默认值
  };
  
  console.log(`Fetching from ${settings.url} with ${settings.method}`);
  // 其他逻辑...
}

利用对象结构的特...option 覆盖默认的参数值

为什么对象参数模式

  1. 可读性:调用时明确知道每个参数的含义

  2. 灵活性

    • 可以不按顺序传递参数

    • 可以只覆盖需要的参数

    • 便于后期扩展新参数而不破坏现有调用

  3. 可维护性:参数变更时只需修改一处默认值


具名参数与默认参数的函数封装
https://halo.jiangling.site/archives/function-skill
作者
你的降灵
发布于
2025年08月13日
许可协议