2

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

dterencio
  • 71
  • 1
  • 7

2 Answers2

5

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]();
AKX
  • 152,115
  • 15
  • 115
  • 172
1

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))
epascarello
  • 204,599
  • 20
  • 195
  • 236