替换 eval(“new object()”) 的最佳方法

dte*_*cio 2 javascript eval draw2d-js

我正在寻找替换 eval("new object();" ) 的最佳方法

丑陋的来源:

    //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);
Run Code Online (Sandbox Code Playgroud)

eval 创建一个新的 sankey.shape.Start 对象。

我正在寻找替换此类代码的最佳解决方案。

谢谢

AKX*_*AKX 5

我将构建一个构造函数的对象(映射)。

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

然后,

const figure = constructors[type]();
Run Code Online (Sandbox Code Playgroud)