Can I use apply() with constructor to pass arbitrary number of parameters

前端 未结 4 555
天命终不由人
天命终不由人 2020-12-10 17:35

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 opera

4条回答
  •  半阙折子戏
    2020-12-10 18:09

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

提交回复
热议问题