我有一个接受任何数量和种类的参数的函数,因此没有定义任何特定的参数.此函数应调用另一个传递所有参数的函数.
问题是我可以传递"参数"以包含所有参数,但在这种情况下,它将像单个参数一样工作,而不是我们期望参数工作的方式.
一个例子:
主要功能:
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' );
Run Code Online (Sandbox Code Playgroud)
使用上面的方法,所有参数将作为伪数组存储在"userid"中,并且可以访问项目,例如arguments [2]但不使用参数名称"param".
在ColdFusion中,这种东西的解决方案是参数"argumentCollection",这样您就可以传递存储在结构中的参数,而不会转换为包含所有键/值的类型struct的单个参数.
我怎样才能用JavaScript实现同样的目标?
use*_*716 39
您可以使用该.apply()方法调用函数并将参数作为集传递.
callSubFunction.apply( this, arguments );
Run Code Online (Sandbox Code Playgroud)
第一个参数将设置的值this在allSubFunction方法.我只是将它设置为当前this值.第二个是要发送的参数集合.
所以你的handleCall()功能看起来像:
function handleCall() {
//set the value of "this" and pass on the arguments object
callSubFunction.apply( this, arguments );
}
Run Code Online (Sandbox Code Playgroud)
您不需要发送Arguments对象.Array如果情况需要,您可以发送一个参数.
ale*_*ngn 38
如果要对扩展语法执行相同操作,可以使用以下命令:
function handleCall(...args) {
callSubFunction(...args);
}
Run Code Online (Sandbox Code Playgroud)