如何在外部函数中获取目标箭头函数的参数?
如何创建一个能返回另一个函数参数的函数?
嘿,我来帮你理清楚这个问题!你想要的是一个工具函数,能拿到另一个函数的参数甚至按位置返回对吧?不过先得指出你示例里的一个小问题:你写的returnArgumentByPosition(returnFirstArgument(foo, hello), 1)里,returnFirstArgument(foo, hello)已经直接执行了,返回的是第一个参数'bar',这时候传给工具函数的是个字符串,不是原函数,自然拿不到它的参数。所以咱们得换个方式传递函数和它的参数。
下面给你几个可行的方案:
方案一:直接传递函数、位置和参数
这个是最直接的写法,让工具函数接收原函数、目标位置,以及原函数需要的所有参数,然后直接返回对应位置的参数:
const returnArgumentByPosition = (fn, position, ...args) => { // 先做个简单的边界校验,避免越界 if (position < 0 || position >= args.length) { throw new Error('参数位置超出有效范围啦') } // 如果你需要执行原函数的话,在这里调用 fn(...args) 就行 // 比如如果要同时拿到原函数返回值和参数,可以这样: // const result = fn(...args); // return { result, arg: args[position] }; // 按需求返回对应位置的参数 return args[position] } // 用起来是这样的: const foo = 'bar' const hello = 'world' const returnFirstArgument = (val1, val2) => val1 const secondArg = returnArgumentByPosition(returnFirstArgument, 1, foo, hello) console.log(secondArg) // 输出 'world'
方案二:柯里化写法,更灵活的调用
如果想让调用方式更灵活,可以用柯里化把参数拆分,先传原函数,再传位置,最后传参数:
const returnArgumentByPosition = (fn) => (position) => (...args) => { if (position < 0 || position >= args.length) { throw new Error('参数位置不对哦') } // 同样,需要执行原函数的话在这里调用 return args[position] } // 使用示例: const getArgFromFn = returnArgumentByPosition(returnFirstArgument) const secondArg = getArgFromFn(1)(foo, hello) console.log(secondArg) // 输出 'world'
方案三:包装函数,捕获参数同时执行原函数
如果你既想执行原函数,又想在之后随时获取它的参数,可以给原函数做个包装,把参数存起来:
const wrapToCaptureArgs = (fn) => { const wrappedFn = (...args) => { // 把参数存到函数的属性上,方便后续获取 wrappedFn.capturedArgs = args // 执行原函数并返回结果 return fn(...args) } return wrappedFn } // 使用示例: const wrappedReturnFirst = wrapToCaptureArgs(returnFirstArgument) const fnResult = wrappedReturnFirst(foo, hello) // 这里执行原函数,返回 'bar' console.log(wrappedReturnFirst.capturedArgs[1]) // 随时获取第二个参数,输出 'world'
总结一下
- 核心要点是别提前执行目标函数,要么把函数和参数一起传给工具函数,要么用包装器捕获参数;
- 如果只是需要返回参数,工具函数里甚至可以不用调用原函数;
- 如果需要执行原函数同时保留参数,包装器是个很实用的办法。
内容的提问来源于stack exchange,提问作者John Winston
相关产品推荐
相关产品推荐

