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

后端 未结 30 3190
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:03

    I just came across this problem, and I solved it like this:

    function instantiate(ctor) {
        switch (arguments.length) {
            case 1: return new ctor();
            case 2: return new ctor(arguments[1]);
            case 3: return new ctor(arguments[1], arguments[2]);
            case 4: return new ctor(arguments[1], arguments[2], arguments[3]);
            //...
            default: throw new Error('instantiate: too many parameters');
        }
    }
    
    function Thing(a, b, c) {
        console.log(a);
        console.log(b);
        console.log(c);
    }
    
    var thing = instantiate(Thing, 'abc', 123, {x:5});
    

    Yeah, it's a bit ugly, but it solves the problem, and it's dead simple.

提交回复
热议问题