I constantly find myself passing config values to functions accessing them like this:
我经常发现自己将配置值传递给访问它们的函数,如下所示:
var arg1 = 'test1';
if(isUndefined(config.args.arg1)){
arg1 = config.args.arg1;
}
var arg2 = 'param2';
if(isUndefined(config.args.arg2)){
arg2 = config.args.arg2;
}
var arg3 = '123';
if(isUndefined(config.args.arg3)){
arg3 = config.args.arg3;
}
where I later use them like this:
之后我在这里使用它们:
var url = '<some-url>?id='+arg1+'&='+arg2 +'=' + arg3;
Does jQuery/ExtJS or any other framework provide a solution to access variables like this in a simple way, and give variables a default value?
jQuery / ExtJS或任何其他框架是否以简单的方式提供了这样的访问变量的解决方案,并为变量赋予了默认值?
Something like:
就像是:
getValueOfObject(config,'args.arg3','<default>');
Or is there maybe a standard solution for this.
或者可能有一个标准的解决方案。
NOTE:
注意:
I was also thinking about the common pattern where you have defaults
我也在考虑你有默认值的常见模式
var defaults = {
args: {
args1: ....
}
...
}
and doing an object merge.
并进行对象合并。
And then encoding the object to a param String. But as you can see the object values also sometimes contain parameter names.
然后将对象编码为param String。但正如您所看到的,对象值有时也包含参数名称。
3 个解决方案
#1
46
Generally, one can use the or operator to assign a default when some variable evaluates to falsy:
通常,当某些变量求值为falsy时,可以使用or运算符指定默认值:
var foo = couldBeUndefined || "some default";
so:
所以:
var arg1 = config.args.arg1 || "test";
var arg2 = config.args.arg2 || "param2";
assuming that config.args
is always defined, as your example code implies.
假设始终定义config.args,如示例代码所示。
#3
3
try var options = extend(defaults, userOptions);
try var options = extend(defaults,userOptions);
This way you get all the userOptions and fall back to defaults when they don't pass any options.
通过这种方式,您可以获得所有userOptions,并在未通过任何选项时回退到默认值。
Note use any extend
implementation you want.
注意使用您想要的任何扩展实现。
#1
46
Generally, one can use the or operator to assign a default when some variable evaluates to falsy:
通常,当某些变量求值为falsy时,可以使用or运算符指定默认值:
var foo = couldBeUndefined || "some default";
so:
所以:
var arg1 = config.args.arg1 || "test";
var arg2 = config.args.arg2 || "param2";
assuming that config.args
is always defined, as your example code implies.
假设始终定义config.args,如示例代码所示。
#2
#3
3
try var options = extend(defaults, userOptions);
try var options = extend(defaults,userOptions);
This way you get all the userOptions and fall back to defaults when they don't pass any options.
通过这种方式,您可以获得所有userOptions,并在未通过任何选项时回退到默认值。
Note use any extend
implementation you want.
注意使用您想要的任何扩展实现。