Javascript parameters: Having many parameters with many defaults
I have a function with many parameters and many default value on them.
function foo(p1 ,p2, p3, p4, p5, p6){
var p1 = p1 || 'default1';
var p2 = p2 || 'default2';
var p3 = p3 || 'default3';
var p4 = p4 || 'default4';
var p5 = p5 || 'default5';
var p6 = p6 || 'default6';
}
How can I successfully only define like p1 and p6 only and not the r开发者_如何学Cest?
I know in Scala you can do foo(p1='something1',p6='something6')
You should take an object with properties for parameters.
For example:
function foo(options) {
var p1 = options.p1 || 'default1';
...
}
foo({ p1: 3, p6: "abc" });
You could use one parameter that is an object and do jQuery extend for defaults like:
function foo(args) {
jQuery.extend({
p1: 'default1',
p2: 'default2',
p3: 'default3',
p4: 'default4',
p5: 'default5',
p6: 'default6'
}, args);
}
foo({p1: 'one', p6: 'six'});
Any properties defined in the second parameter to extend will overwrite properties in the first parameter.
Those are referred to as "named parameters", and there are several tutorials on them (using objects like in @SLaks's answer):
http://www.javascriptkit.com/javatutors/namedfunction.shtml (also see page 2 of that on detecting which parameters were passed reliably;
||
doesn't always work)http://www.spheredev.org/smforums/index.php?topic=1678.0
精彩评论