best way to replace an eval( "new object()" )

219 views Asked by At

I m looking for the best way to replace eval( "new object();" )

The ugly source :

    //var type = window.$(droppedDomNode).data("shape");
    var type = "sankey.shape.Start";

    var figure = eval("new "+type+"();");
    
    // create a command for the undo/redo support
    var command = new draw2d.command.CommandAdd(this, figure, x, y);

The eval create a new sankey.shape.Start object.

I'm looking for best solution to replace this kind of code.

Thanks

2

There are 2 answers

3
AKX On

I'd build an object (mapping) of constructor functions.

const constructors = {
  "sankey.shape.Start": () => new sankey.shape.Start(),
  // etc... (this could be built programmatically)
};

Then,

const figure = constructors[type]();
0
epascarello On

You can split it and walk up the path from window if it is global

var foo = {
  bar: {
    world: 'baz',
  }
}

const getIt = (str, start = window) => {
  return str.split(/\./).reduce((o, k) => o[k], start);
}


const x = "foo.bar.world";
console.log(getIt(x))