如何将所有参数作为集合传递给另一个函数而不是作为单个参数?

时间:2011-01-16 15:38:13

标签: javascript

我有一个接受任意数量和种类的参数的函数,因此没有定义任何特定的参数。这个函数应该调用另一个传递所有参数的函数。

问题在于我可以传递“参数”以包含所有参数,但在这种情况下,它将像单个参数一样工作,而不是我们期望参数工作的方式。

一个例子:

主要功能:

function handleCall() {
   // let's call a sub-function
   // and pass all arguments (my question is how this is handled the right way)
   function callSubFunction( arguments );
}

function callSubfunction( userid, customerid, param) {
   // passed arguments are now 
   alert( 'userid = ' + userid );

   // this will not work, you have to use arguments[2]
   alert( param );
  }

The example call:

handleCall( 1029, 232, 'param01' );

使用上述方法,所有参数将作为伪数组存储在“userid”中,并且可以访问项目,例如arguments [2]但不使用参数名称“param”。

在ColdFusion中,这种东西的解决方案是参数“argumentCollection”,这样你就可以传递存储在结构中的参数,而不用转换为包含所有键/值的struct类型的单个参数。

如何使用JavaScript实现相同的目标?

3 个答案:

答案 0 :(得分:37)

您可以使用the .apply() method来调用函数并将参数作为集合传递。

callSubFunction.apply( this, arguments ); 

第一个参数将在this方法中设置allSubFunction的值。我只是将其设置为当前this值。第二个是要发送的参数集合。

因此,您的handleCall()函数将如下所示:

function handleCall() {
     //set the value of "this" and pass on the arguments object
    callSubFunction.apply( this, arguments );
}

您不需要发送Arguments个对象。如果需要,您可以发送Array个参数。

答案 1 :(得分:29)

如果您想对spread syntax执行相同操作,可以使用以下内容:

function handleCall(...args) {
    callSubFunction(...args);
}

答案 2 :(得分:1)

使用如下所示:

function Foo()
{
    Bar.apply(this, arguments);
}

function Bar(a, b)
{
    alert(a);
    alert(b);
}