我有一个看起来像这样的函数:
function f(requiredParamA, requiredParamB, optionalObjectParamA, optionalObjectParamB) {
optionalObjectParamA = optionalObjectParamA || {};
optionalObjectParamB = optionalObjectParamB || {};
// rest of the function
}
假设我想使用 optionalObjectParamB
的值调用 f
,但不使用 optionalObjectParamA
的值。我可以这样做:
f("john", 100, null, {vegatarian: true});
但这会导致 API 变得丑陋。 还有其他选择吗?我应该如何设计该函数以及如何调用它?
最佳答案
传递对象而不是参数。然后你就可以拥有无限的可选参数,而无需炸毁你的参数列表。
function f(requiredParamA, requiredParamB, context) {
var optional = context || {};
// handle optional.optionalObjectParamA..
// handle optional.optionalObjectParamB..
}
关于javascript - 如何避免将空参数传递给具有多个可选参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33247801/