【问题标题】:How to pass all arguments as collection to another function and not as single argument? [duplicate]如何将所有参数作为集合传递给另一个函数而不是作为单个参数? [复制]
【发布时间】:2011-06-10 00:36:51
【问题描述】:

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

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

一个例子:

主要功能:

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”,这样您可以传递存储在结构中的参数,而无需转换为包含所有键/值的类型结构的单个参数。

我怎样才能用 JavaScript 达到同样的效果?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    如果你想对spread syntax 做同样的事情,你可以使用以下:

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

    【讨论】:

    • 对于打字稿,我们可以提取函数参数的类型并使用它来输入其余的参数: type handleCallParams = Parameters;
    • 好东西!
    • 对于带有构造函数和调用 super 的 typescript,可以使用ConstructorParameters<typeof BaseClass>
    【解决方案2】:

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

    callSubFunction.apply( this, arguments ); 
    

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

    所以你的handleCall() 函数看起来像:

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

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

    【讨论】:

    • 在ES6函数中怎么做?
    • 这里的文档链接是dead。正确修复链接的My edit 被两个用户拒绝,并带有相同复制粘贴关于“可读性”的消息,尽管该消息不影响可见文本。 (我怀疑他们是在为网站代表进行耕种/博弈。)同时,这是 MDN 的 Function.prototype.apply() 的工作链接:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    【解决方案3】:

    像这样使用 apply:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-07
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2019-08-19
      相关资源
      最近更新 更多