JavaScript - 如何将新实例设置为动态创建的参数?

JavaScript - How to set new instance as parameter, created dynamically?

我有一个方法可以将新实例设置为动态创建的数组。如果不使用 eval() 我该怎么做?

var Form = (function(){
    function Form(params){
        this.shapesArray = [];
        this.shape;
        ...
    }

    Form.prototype.submit = function(){
        ... this.shape is the shape selected by the user ...
        this.setShape('new Shapes.' + this.shape + '(arg1, arg2, color)');
    }

    Form.prototype.setShape = function(obj){
        this.shapesArray.push(obj);
    }
return Form;
}());

那么,如何在没有 eval() 的情况下通过传递 new 实例来调用 setShape 方法?

目前有效:

Form.prototype.submit = function(){
    eval('this.setShape(new Shapes.'+ this.shape.capitalize() +'('+ str_params + '))');
}

但是使用 eval() 并不是一个好习惯。如何在没有 eval() 的情况下获得相同的结果?

您可以使用 bracket notation 访问 属性 :

this.setShape(new Shapes[this.shape](arg1, arg2, color));

现在,如果您从动态数组中获取参数,它会稍微复杂一些,因为您不能只使用 apply

这是一个解决方案:

var constructor = new Shapes[this.shape];
var C = function(){
    return constructor.apply(this, arr_of_args);
}
C.prototype = constructor.prototype;
this.setShape(new C());

但这开始变得棘手且难以阅读。不涉及具有可变数量参数的动态构造函数的应用程序的新设计可能更可取。