我可以使用适用()与构造函数传递参数的任意数 [英] Can I use apply() with constructor to pass arbitrary number of parameters

查看:202
本文介绍了我可以使用适用()与构造函数传递参数的任意数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数至极可以接受参数的varible号码与休息运营商。

我要创建合格,其余的运营商收取的参数直接构造不创建一个对象,并调用初始化函数,而没有经过整个阵列的对象,但在参数啊我做的apply()函数。

这可能吗?使用应用无法正常工作。

 公共职能myFunc的(... ARG){

     //一些链接新MyClass.apply(参数)
     返回新MyClass的();

}
 

解决方案

不幸的是没有。有没有办法让申请工作的构造。什么是一般做的是prepare一些呼叫基础上的参数个数:

 公共职能myFunc的(... ARG):MYCLASS {
  开关(arg.length){
    情况下0:返回新MyClass的();
    案例1:返回新MyClass的(ARG [0]);
    案例2:返回新MyClass的(ARG [0],ARG [1]);

    //... 等等

    当n:返回新MyClass的(ARG [0],ARG [1],...,ARG [N]);
    默认:抛出新的错误(在myFunc的太多争论);
  }
}
 

I've got a function wich can accept a varible number of parameter with a rest operator.

I want create an object passing the argument collected with the rest operator directly to a constructor without create an object and call an initializing function and without passing the entire array but the parameters ah I do with apply() function.

Is it possible ? Using apply doesn't work.

public function myFunc(...arg) {

     // something link "new MyClass.apply(args)"
     return new MyClass();

}

解决方案

Unfortunately no. There is no way to make apply work for constructor. What is done generally is to prepare a number of call based on the number of arguments :

public function myFunc(...arg):Myclass {
  switch (arg.length) {
    case 0:return new MyClass();
    case 1:return new MyClass(arg[0]);
    case 2:return new MyClass(arg[0], arg[1]);

    //... etc

    case n:return new MyClass(arg[0], arg[1],..,arg[n]);
    default: throw new Error("too much arguments in myFunc");
  }
}

这篇关于我可以使用适用()与构造函数传递参数的任意数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆