Use of .apply() with 'new' operator. Is this possible?

后端 未结 30 2747
Happy的楠姐
Happy的楠姐 2020-11-22 00:39

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

30条回答
  •  逝去的感伤
    2020-11-22 01:06

    Actually the simplest method is:

    function Something (a, b) {
      this.a = a;
      this.b = b;
    }
    function createSomething(){
        return Something;
    }
    s = new (createSomething())(1, 2); 
    // s == Something {a: 1, b: 2}
    

提交回复
热议问题