在运行时创建对象

Ste*_*eve 0 javascript

我有一个简单的工厂,我想简化,每次添加一个我想要返回的新对象时都不需要修改.在Javascript中,我如何能够在运行时创建对象?谢谢

switch (leagueId) {
  case 'NCAAF' :
      return new NCAAFScoreGrid();
  case 'MLB' :
      return new MLBScoreGrid();
  ... 
}
Run Code Online (Sandbox Code Playgroud)

eph*_*ent 6

var leagues = {
    'NCAAF': NCAAFScoreGrid,
    'MLB':   MLBScoreGrid,
    // ...
};  // maybe hoist this dictionary out to somewhere shared

if (leagues[leagueId]) {
    return new leagues[leagueId]();
}
// else leagueId unknown
Run Code Online (Sandbox Code Playgroud)