如何多次调用此默认args函数? [英] How to call this default args function more than once?
问题描述
我遇到了一个问题,我需要允许在JavaScript中的函数上设置默认参数:
I have encountered a question where I need to allow default args to be set on a function in JavaScript:
function dfltArgs(func, params) {
const strFn = func.toString()
console.log(strFn)
const args = /\(([^)]+)\)/.exec(strFn)[1].split(',')
const defaultVal = (arg, val) => typeof arg !== 'undefined' ? arg : val
return (...dynamicArgs) => {
const withDefaults = args.map((arg, i) =>
defaultVal(dynamicArgs[i], params[args[i]]))
return func(...withDefaults)
}
}
function add (a, b) { return a + b }
var add_ = dfltArgs(add,{b:9})
console.log(add_(10)) // Should be 19
var add_ = dfltArgs(add_,{b:3})
console.log(add_(10)) // Should now be 13
但是,我需要才能多次调用此函数并覆盖先前设置的默认值:
However, I need to be able to call this function more than once and overwrite previously set defaults:
var add_ = defaults(add,{b:9})
add_(10) // Should be 19
var add_ = defaultArguments(add_,{b:3})
add_(10) // Should now be 13
这在我的实现中不起作用,因为第二个调用的字符串化函数是: (... dynamicArgs)=> {
等。
This does not work in my implementation, because the stringified function on the second call is: (...dynamicArgs) => {
, etc.
我该如何重构?可能需要以某种方式使用 bind
?
How can I refactor this? Probably need to use bind
somehow?
推荐答案
代替复杂的默认设置关于args的事情,为什么不只使用带有真正默认参数的箭头函数:
Instead of your complicated default args thing, why not just use some arrow functions with real default arguments:
var _add = (a, b = 8) => add(a, b);
这样,您可以轻松更改绑定的东西:
That way you can easily change the bound things:
var add_ = (a = 2, b) => _add(a, b);
add_() // 10
这篇关于如何多次调用此默认args函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!