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

后端 未结 30 3159
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:08

    function createSomething() {
        var args = Array.prototype.concat.apply([null], arguments);
        return new (Function.prototype.bind.apply(Something, args));
    }
    

    If your target browser doesn't support ECMAScript 5 Function.prototype.bind, the code won't work. It is not very likely though, see compatibilty table.

提交回复
热议问题