javascript long list of parameter; looking for alternative
I'm writing a javascri开发者_开发问答pt function that has a pretty long list of parameters:
FormatGrid(ID, BackColor, SideColor, HiddenColor, SmallTextClass....)
It works well but it's getting somewhat painful when calling this function to remember each parameter and the order they go in because the function takes a total of 9 parameters (and I might add 2 more).
I'm wondering if there's an elegant solution to this.
Thanks for your suggestions.
you can just pass in an Object
FormatGrid(myObject){
//your code
}
Where your myObject is something like {ID: '1', BackColor: 'red', SideColor: 'red', HiddenColor: 'black', SmallTextClass: 'true'...}
Generally I like the following format
function foo(requiredVar1,requiredVar2,..,options) {
//here is where options is merged with default params
var defaultOptions = {};
options = Object.extend(defaultOptions,(options || {}));
}
where options is a map {option1:value1, ...}
Pass an object to your function as a parameter:
function FormatGrid(objectParameter) {
// ...
}
FormatGrid({
key1: "val1",
key2: "val2",
...
});
also, you can merge the given function parameters with default ones like this:
function mergeWithDefaults (params, defaults={}) {
var toRet = {};
for (atr in defaults)
toRet[atr] = defaults[atr];
for (atr in params)
toRet[atr] = params[atr];
return toRet;
}
Then you can use this function to "default" parameters, in your function:
FormatGrid (params) {
params = mergeWithDefaults (params, { 'backColor': '0xfff' });
// Body of your function using the params variable which has been defaulted.
}
If you call FormatGrid with params containing backColor it will be used, else it will be defaulted to the default ('0xfff' here).
i hope this helps :) Pierre.
An alternative to using an options/params object is to create new versions of the function that have some values already filled in. This is useful when you need to repeatedly call the same function without changing the values of many of the arguments.
// bad name; a good name would say something about
// the purpose of the new function
function makeShorterFormatGrid(ID, BackColor, SideColor) {
return function(HiddenColor, SmallTextClass) {
FormatGrid(ID, BackColor, SideColor, HiddenColor, SmallTextClass);
}
}
var ShortFormatGrid = makeShorterFormatGrid("myId", "#ffffff", "#000000");
// the first three arguments are already filled in
ShortFormatGrid("#c0c0c0", "className");
ShortFormatGrid("#cccccc", "otherClassName");
精彩评论