You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动将对象子属性用指定函数封装,无需手动逐个处理?

实现方案

你可以写一个通用的属性遍历封装函数,自动把每个controller下的方法用executeRequest包裹,不需要手动逐个处理:

// 通用单层封装工具函数,适配大多数controller只有一层方法的场景
const wrapControllerMethods = (controller) => {
  const wrapped = {}
  // 遍历controller的所有属性
  for (const [key, value] of Object.entries(controller)) {
    // 仅对函数类型的属性做executeRequest包裹
    if (typeof value === 'function') {
      // 如果方法内部依赖this指向原controller,可改成executeRequest(value.bind(controller))
      wrapped[key] = executeRequest(value)
    } else {
      // 非函数类型的常量/配置属性直接保留
      wrapped[key] = value
    }
  }
  return wrapped
}

之后你的controllers定义就可以按照你期望的写法实现:

import authController from "./authController";
import appController from "./appController";
import userController from "./userController";
import postController from "./postController";
import { executeRequest } from "./utils";

const wrapControllerMethods = (controller) => {
  const wrapped = {}
  for (const [key, value] of Object.entries(controller)) {
    if (typeof value === 'function') {
      wrapped[key] = executeRequest(value)
    } else {
      wrapped[key] = value
    }
  }
  return wrapped
}

const controllers = {
  user: wrapControllerMethods(userController),
  auth: wrapControllerMethods(authController),
  post: wrapControllerMethods(postController),
  app: wrapControllerMethods(appController)
};

进阶优化

如果你的controller存在多层嵌套的方法,或者想要进一步简化写法,可以改用递归封装+批量处理的版本:

// 递归版本,支持任意层级的嵌套方法封装
const wrapControllerMethods = (controller) => {
  if (typeof controller !== 'object' || controller === null) return controller
  if (typeof controller === 'function') return executeRequest(controller)
  const wrapped = Array.isArray(controller) ? [] : {}
  for (const [key, value] of Object.entries(controller)) {
    wrapped[key] = wrapControllerMethods(value)
  }
  return wrapped
}

// 批量封装工具
const wrapAllControllers = (rawControllers) => {
  return Object.fromEntries(
    Object.entries(rawControllers).map(
      ([name, controller]) => [name, wrapControllerMethods(controller)]
    )
  )
}

// 最终定义方式,后续新增controller只需在对象内加一行即可自动完成封装
const controllers = wrapAllControllers({
  user: userController,
  auth: authController,
  post: postController,
  app: appController
})

封装完成后使用方式和你的预期完全一致,无需修改下游调用代码。

内容的提问来源于stack exchange,提问作者NhLe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 09:48:02