How can I construct an object using an array of values for parameters, rather than listing them out, in JavaScript?

前端 未结 5 500

Is this possible? I am creating a single base factory function to drive factories of different types (but have some similarities) and I want to be able to pass arguments as

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 12:32

    One possibility is to make the constructor work as a normal function call.

    function MyClass(arg1, arg2) {
        if (!(this instanceof MyClass)) {
            return new MyClass(arg1, arg2);
        }
    
        // normal constructor here
    }
    

    The condition on the if statement will be true if you call MyClass as a normal function (including with call/apply as long as the this argument is not a MyClass object).

    Now all of these are equivalent:

    new MyClass(arg1, arg2);
    MyClass(arg1, arg2);
    MyClass.call(null, arg1, arg2);
    MyClass.apply(null, [arg1, arg2]);
    

提交回复
热议问题