我有Movie
和Actor
个类。我需要添加一个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)
在其中添加演员?如果是这样,我该怎么做?
答案 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