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

后端 未结 30 2726
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 00:59

    if you're interested in an eval-based solution

    function createSomething() {
        var q = [];
        for(var i = 0; i < arguments.length; i++)
            q.push("arguments[" + i + "]");
        return eval("new Something(" + q.join(",") + ")");
    }
    

提交回复
热议问题