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

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

    Thanks to posts here I've used it this way:

    SomeClass = function(arg1, arg2) {
        // ...
    }
    
    ReflectUtil.newInstance('SomeClass', 5, 7);
    

    and implementation:

    /**
     * @param strClass:
     *          class name
     * @param optionals:
     *          constructor arguments
     */
    ReflectUtil.newInstance = function(strClass) {
        var args = Array.prototype.slice.call(arguments, 1);
        var clsClass = eval(strClass);
        function F() {
            return clsClass.apply(this, args);
        }
        F.prototype = clsClass.prototype;
        return new F();
    };
    

提交回复
热议问题