有没有办法清理javascript中的子类参数?

时间:2018-12-09 19:22:04

标签: javascript class parameters subclass superclass

我正在尝试使用JavaScript中的子类,并且正在使用Marvel电影来做到这一点。这是我的超类:

class Episode {
  constructor(title, releaseDate, storyYear, phase, order, runtime, hero){
    this.title = title;
    this.releaseDate = releaseDate;
    this.releaseMonth = parseInt(releaseDate.split('/')[0]);
    this.releaseYear = parseInt(releaseDate.split('/')[1]);
    this.episodeType = "";
    this.storyYear = storyYear;
    this.phase = phase;
    this.order = order;
    this.runtime = runtime;
    this.hours = parseInt(runtime.split(':')[0]);
    this.minutes = parseInt(runtime.split(':')[1]);
    this.hero = hero;
  }
} 

现在,我创建了3个子类。一种用于电影,一种用于电视节目,一种用于“一枪”。通过这种方式,我可以添加更多信息,例如电视季,剧集以及一张照片属于哪个DVD。

  class Movie extends Episode {
    constructor(title, releaseYear, storyYear, phase, order, runtime, hero){
      super(title, releaseYear, storyYear, phase, order, runtime, hero);
      this.episodeType = "Movie";
    }
  }
  class TVShow extends Episode {
    constructor(title, releaseYear, storyYear, phase, order, runtime, hero, episode){
      super(title, releaseYear, storyYear, phase, order, runtime, hero);
      this.episodeType = "TV Show";
      this.episode = episode;
    }
  }
  class OneShot extends Episode {
    constructor(title, releaseYear, storyYear, phase, order, runtime, hero){
      super(title, releaseYear, storyYear, phase, order, runtime, hero);
      this.episodeType = "One Shot";
    }
  }

我看到的问题是,如果我必须将构造函数添加到原始情节中,还必须将其也添加到每个子类中。这是最有效的方法吗?

1 个答案:

答案 0 :(得分:0)

如@Bergi所建议的那样,您可以使用参数列表,而不是显式定义每个参数,例如

Array
(
    [aoepeople/scheduler] => v1.6.13
    [nwdthemes/revslider] => dev-master
    [churiart/blogomatic] => dev-master
    [php-pm/php-pm] => v1.0.4
    .
    .
    .

这样,您可以获得更简洁的代码,并避免在所有地方列出所有参数。但是,您将丢失所有参数的隐式定义,并且可能希望手动实现一些约束。例如如果class Episode{ constructor(args) { this.args = args; } } class Movie extends Episode{ constructor(args){ args.episodeType = 'Movie'; super(args); } } // The same for all subclasses 未定义或为空,则会引发错误。