Javascript parameters: Having many parameters with many defaults

。_饼干妹妹 提交于 2019-12-23 03:19:17

问题


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 rest?

I know in Scala you can do foo(p1='something1',p6='something6')


回答1:


You should take an object with properties for parameters.

For example:

function foo(options) {
    var p1 = options.p1 || 'default1'; 
    ...
}

foo({ p1: 3, p6: "abc" });



回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/4982223/javascript-parameters-having-many-parameters-with-many-defaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!