Javascript 在另一个类中添加一个或多个类实例
我有Javascript 在另一个类中添加一个或多个类实例,javascript,html,class,methods,attributes,Javascript,Html,Class,Methods,Attributes,我有电影和演员课程。我需要添加一个addCast(cast)方法,允许在电影中添加一个或多个演员 我已经: class Movie{ constructor(name, year, duration){ this.name = name; this.year = year; this.duration = duration; } } class Actor{ constructor(name, age){ t
电影
和演员
课程。我需要添加一个addCast(cast)
方法,允许在电影中添加一个或多个演员
我已经:
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;
}
}
我应该能够做如下事情:
《终结者》艾德卡斯特(阿诺德)
终止符。addCast(其他cast)//otherCast可以是参与者的数组
我该怎么做
我是否需要添加一个actors
属性(在Movie
中)来使用addCast(cast)
添加演员?如果是这样的话,我该怎么做呢?类似于以下内容的功能可以发挥作用(适应您的需要):
类似于以下的方法可能会起作用(适应您的需要):
张贴你所学课程的代码?通常,您可以执行terminator.addCast=function(…
等操作。发布您拥有的类的代码?通常,您可以执行terminator.addCast=function(…
等操作。
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