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

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

问题描述

我有一个函数,它可以接受带有休息运算符的可变数量的参数.

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

我想创建一个对象,将使用 rest 运算符收集的参数直接传递给构造函数,而无需创建对象并调用初始化函数,也无需传递整个数组但参数啊我用 apply() 函数做的.

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.

有可能吗?使用 apply 不起作用.

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");
  }
}

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

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