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

switch (leagueId) {
  case 'NCAAF' :
      return new NCAAFScoreGrid();
  case 'MLB' :
      return new MLBScoreGrid();
  ...
}

最佳答案

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

if (leagues[leagueId]) {
    return new leagues[leagueId]();
}
// else leagueId unknown

08-17 00:41