在另一个类中添加一个或多个类的实例

时间:2018-05-19 18:43:47

标签: javascript html class methods attributes

我有MovieActor个类。我需要添加一个addCast(cast)方法,允许在电影中添加一个或多个Actors

我已经拥有:

class Movie{
    constructor(name, year, duration){
        this.name = name;
        this.year = year;
        this.duration = duration;
    }
}
class Actor{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

我应该可以做类似的事情:

  

terminator.addCast(阿诺德);

     

terminator.addCast(otherCast); // otherCast可以是Actor

数组

我该怎么做?

我是否需要添加actors属性(在Movie中)以使用addCast(cast)在其中添加演员?如果是这样,我该怎么做?

1 个答案:

答案 0 :(得分:2)

以下内容可以起作用(适应您的需求):

class Movie{
    constructor(name, year, duration){
        this.name = name;
        this.year = year;
        this.duration = duration;
        this.cast = []; // initialy we have an empty cast, to be added by addCast
    },
    addCast(cast){
       // in general it can accept an array of actors or a single actor
       if ( cast instanceof Actor) {
           cast = [cast]; // make it an array
       }
       for(var i=0; i<cast.length; i++) {
          this.cast.push(cast[i]);
       }
       return this; // make it chainable
    }
}

然后你可以像这样添加演员:

terminator.addCast(new Actor('Arnold', 47)); // add single actor as cast
terminator.addCast([
  new Actor('An Actor', 30),
  new Actor('Another Actor', 40),
]); // add array of actors