0

At the moment I am using eval() to create an object dynamically, function constructor called is actually in closure.

The string in eval(), in my real app code is created based on a condition.

I would like to know if it is possible to achieve the same result avoid using eval().

I would be interested in a solution which avoiding adding Icon and Logo to windowglobal, and using syntax like window[myDesiredFunction] when declaring the new object. Also I cannot use any hard-coded switch case statements.

(function(window){
    var Icon = function(id){
       this.id = id;
    };
    var Logo = function(id){
       this.id = id;
    };
    var app = {
        start:function(){
            var item1 = eval("new Icon('iconA')");  // i need replace eval()
            var item2 = eval("new Logo('logoB')");  // just as example string will be created with some condition dynamically
            console.log(item1 .id);
            console.log(item2 .id);
        }
    };
    app.start();
})(window);
GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    Can you please give some data which you want to convert in eval – Mitul Jul 14 '16 at 08:47
  • 3
    well create an object wich will store these two constructors (then call it like `new myConstructors['Icon']('iconA')`) – Kaiido Jul 14 '16 at 08:48
  • 2
    `var constructors = { Icon : Icon, Logo : Logo }; var item1 = new constructors["Icon"]("iconA");` – nnnnnn Jul 14 '16 at 08:49

1 Answers1

1

You need to store your constructors in an object, and if you want to use a variable number of arguments you need use the technique described here Use of .apply() with 'new' operator. Is this possible?.

The resulting code will look like this:

(function(window) {
  function Icon(id) {
    this.id = id;
  }

  function Logo(id) {
    this.id = id;
  }

  var constructors = {
    Icon: Icon,
    Logo: Logo
  }


  function createObject(name, arguments) {
    var args = Array.prototype.slice.call(arguments);
    args.unshift(null);
    return new(Function.prototype.bind.apply(constructors[name], args));
  }

  var app = {
    start: function() {
      var item1 = createObject('Icon', ['iconA']);
      var item2 = createObject('Logo', ['logoB']);
      console.dir(item1);
      console.dir(item2);
    }
  };
  app.start();
})(window);
Community
  • 1
  • 1
t.niese
  • 39,256
  • 9
  • 74
  • 101