【问题标题】:JavaScript - How to set new instance as parameter, created dynamically? [duplicate]JavaScript - 如何将新实例设置为参数,动态创建? [复制]
【发布时间】:2015-07-29 23:55:14
【问题描述】:

我有一个方法可以将新实例设置为动态创建的数组。如果不使用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(),如何达到同样的效果?

【问题讨论】:

    标签: javascript string oop object instance


    【解决方案1】:

    您可以使用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());
    

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

    【讨论】:

    • 谢谢。好像它正在工作。如果参数的数量也是动态创建的,我如何传递参数?我怎样才能设法使用apply?类似this.setShape(new Shapes[this.shape].apply(null, arr_of_args));
    • @Ezio_ 见编辑。但我显然不会使用如此复杂的东西来创建实例,您的应用程序可能有更好的设计(例如,可能是工厂地图)。
    • 谢谢伙计。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多