Dynamic instantiation in JavaScript

前端 未结 3 984
情歌与酒
情歌与酒 2020-12-15 22:54

Apart from eval, is there any other way to instantiate an object using variable argument list?

E.g.: var foo = instantiate(className, [arg1, arg2, ...])

3条回答
  •  时光说笑
    2020-12-15 23:30

    Using Object.create() in ES5:

    function instantiate(constructor, args) {
        var instance = Object.create(constructor.prototype);
        constructor.apply(instance, args);
        return instance;
    }
    

    Using the spread operator in ES6:

    var foo = new constructor(...args);
    

提交回复
热议问题